您的位置:首页 > 编程语言 > ASP

使用ASP.NET上传多个文件到服务器

2013-10-13 19:21 417 查看
在Email系统中经常会上传多个文件到服务器,用户大多习惯一次上传所有的文件,而不是逐个上传,我们可以使用javascript动态地添加file元素到表单,然后在服务器端处理这些file

效果图如下:



页面代码MutlileFileUpload.aspx如下:

[html] view
plaincopy

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MutlileFileUpload.aspx.cs"

Inherits="MutlileFileUpload" %>

<!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>

<title>多文件上传到服务器Demo</title>

<link href="css/writemail.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">

<!--

var MAXFILES = 5; //文件计数器

var fileCount = 0;

function addAttach(noAlert) {

if (fileCount >= MAXFILES && !noAlert) { alert("最多只能添加" + MAXFILES + "个附件!"); return; }

var fileSectionDiv = document.getElementById("files");

var fileItemDiv = document.createElement("div");

fileCount++;

var content = "<input type='file' onchange='return addAttach(true);' name='fileUpload'" + fileCount + "> <a href='#' onclick='return delAttach(\"" + fileCount + "\")' class='delete_attach' >移除附件</a>";

fileItemDiv.id = "fileItemDiv" + fileCount;

fileItemDiv.innerHTML = content;

fileSectionDiv.appendChild(fileItemDiv);

return false;

}

function delAttach(fileIndex) {

var fileSectionDiv = document.getElementById("files");

var fileItemDiv = document.getElementById("fileItemDiv" + fileIndex);

fileSectionDiv.removeChild(fileItemDiv);

fileCount--;

return false;

} //

--></script>

</head>

<body>

<form id="form1" runat="server">

<div>

<a id="addAttach_a" onclick="return addAttach(false);" href="#" class="add_attach">添加附件</a>

<div id="files">

</div>

<asp:Button ID="btnSend" runat="server" Text="发送" OnClick="btnSend_Click" />

</div>

</form>

</body>

</html>

样式表WriteMail.css代码如下:

[css] view
plaincopy

.delete_attach {PADDING-LEFT: 18px; BACKGROUND: url(../images/deleteattch_icon.gif) no-repeat left top; MARGIN-LEFT: 7px; WIDTH: 90px; COLOR: #002f76}.add_attach {PADDING-LEFT: 22px; BACKGROUND: url(../images/attach.gif) no-repeat left center; WIDTH: 90px; COLOR: #002f76}

后台代码MutlileFileUpload.aspx.cs如下:

[csharp] view
plaincopy

using System;

using System.IO;

using System.Web.UI;

public partial class MutlileFileUpload : System.Web.UI.Page

{

protected void Page_Load(object sender, System.EventArgs e)

{ //告诉表单如何格式化文件信息

Page.Form.Enctype = "multipart/form-data";

}

protected void btnSend_Click(object sender, EventArgs e)

{

for (int index = 0; index < Request.Files.Count; index++)

{

if (!string.IsNullOrEmpty(Request.Files[index].FileName))

{

Request.Files[index].SaveAs(Path.Combine(Server.MapPath("Files"), System.IO.Path.GetFileName(Request.Files[index].FileName)));

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: