1 前台代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>
<!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 id="Head1" runat="server">
<title>批量上传</title>
<script src="jquery/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var count = 1; //上传组件个数
$(function () {
//添加上传组件
$("#btnAdd").click(function () {
// if ($("#DivUploads").find(":button").length >= 7) {
// alert('最多只能添加八个上传组件!');
// return;
// }
var strHtml = '<span><input type="file" name="fileUpload" runat="server" />';
strHtml += "<input type='button' οnclick='delUploadBtn(" + count + ")' value='删除'/></span>";
$("#DivUploads").append(strHtml);
count++;
});
});
//删除上传组件
function delUploadBtn(index) {
$("#DivUploads").find(":button").each(function () {
var text = "" + $(this).attr("onclick");
if (text.indexOf("delUploadBtn(" + index + ")") != -1) {
$(this).parent().remove();
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<%-- <asp:LinkButton ID="btnAdd" runat="server">添加</asp:LinkButton>--%>
<input type="button" id="btnAdd" value="添加" />
<div id="DivUploads" style="border: 0px solid; width: 300px; height: auto;">
</div>
<asp:Button ID="btnUpload" runat="server" Text="上传" OnClick="btnUpload_Click" />
</form>
</body>
</html>
2 后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 上传处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
//获取页面控件的值
string filepath = Request.Form["fileUpload"];
//上传文件保存路径
string savePath = Server.MapPath("UploadFiles") + "\\";
//HttpFileCollection 提供对客户端上载文件的访问
//获取所有上传文件
HttpFileCollection uploadFiles = System.Web.HttpContext.Current.Request.Files;
try
{
for (int i = 0; i < uploadFiles.Count; i++)
{
//HttpPostedFile 对已上传文件进行操作
//uploadFiles[i] 逐个获取上传文件
System.Web.HttpPostedFile postedFile = uploadFiles[i];
string savePath = postedFile.FileName;//完整的路径
fileName = System.IO.Path.GetFileName(postedFile.FileName); //获取到名称
string fileExtension = System.IO.Path.GetExtension(fileName);//文件的扩展名称
string type = fileName.Substring(fileName.LastIndexOf(".") + 1); //类型
if (uploadFiles[i].ContentLength > 0)
uploadFiles[i].SaveAs(savePath + fileName);
}
}
catch (System.Exception Ex)
{
Response.Write(Ex);
}
}
}