<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileTest.aspx.cs" Inherits="MyShop.Web.FileTest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function addfile() {
$("#td_file").find("tbody").append("<tr><td>上传文件:<input type='file' id='file1' name='file1' /> <a href='#' onclick='delfile(this);'>删除</a></td></tr>");
}
function delfile(obj) {
$(obj).parent().parent().remove();
}
</script>
</head>
<body>
<form id="form1" runat="server" method="post" enctype="multipart/form-data" action="FileTest.aspx">
<div>
<input type="button" value="继续添加" onclick="addfile();" />
<table id="td_file">
<tr>
<td>
上传文件:<input type="file" id="file1" name="file1" /> <a href="#" onclick="delfile(this);">删除</a>
</td>
</tr>
</table>
<input type="submit" value="提交" />
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyShop.Web
{
public partial class FileTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST")
{
HttpFileCollection files = HttpContext.Current.Request.Files;
StringBuilder log = new StringBuilder();
for (int i = 0; i < files.Count; i++)
{
log.Append("***********第" + (i + 1) + "个文件上传开始***********</br>");
HttpPostedFile postFile = files[i];
string filename;//文件名
string fileExtension;//文件后缀名
filename = Path.GetFileName(postFile.FileName);
fileExtension = Path.GetExtension(postFile.FileName);
//上传后的文件名
filename = DateTime.Now.ToString("yyyyMMdd") + "_" + filename;
//上传路径
string directory = Server.MapPath("~/uploadFiles/");
//文件全路径
string path = directory + filename;
//判断目录是否存在
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
//文件存在就删除
if(File.Exists(path))
{
File.Delete(path);
}
log.Append("上传的文件类型:" + postFile.ContentType + "</br>");
log.Append("客户端文件地址:" + postFile.FileName + "</br>");
log.Append("上传文件的文件名:" + filename + "</br>");
log.Append("上传文件的扩展名:" + fileExtension + "</br>");
postFile.SaveAs(path);
log.Append("***********第" + (i + 1) + "个文件上传结束***********</br>");
}
Response.Write(log.ToString());
}
}
}
}