想實現任意多個檔案上傳的功能,點擊一次按鈕可以新增一個檔案上傳框,以前在網路硬碟上看過。 JavaScript我知道怎麼實作任意新增上傳檔案控件,問題是新增的是Html控件,我不懂怎麼讓伺服器端可以取得檔案。
於是上google搜尋“ASP.NET 多文件上傳”,還真找到一篇文件,標題為《在ASP.NET中實現多文件上傳》,文章裡面是VB.NET實現的,功能和我要的一模一樣,我主要要看伺服器端怎麼取得客戶端上傳的文件,看了文中的程式碼,原來這麼簡單,System.Web.HttpContext.Current.Request.Files就包含客戶端瀏覽器上傳的文件了,我用C#寫了一段簡單的程式碼,原本以為應該可以了,結果出乎意料上傳3個圖片System.Web.HttpContext.Current.Request.Files回傳的檔案格式還是0個。
不知道什麼原因,看看程式碼,這麼簡單不可能些錯啊,再看看google搜尋結果裡的另外幾篇文章,發現我看的第一篇不是原做,作者的網站上原作的實例有兩個版本,一個是VB.NET一個是C#的,現在我不用自己寫了,複製原文的程式碼到本地,運行,果然可以啊,那我寫的程式碼怎麼不行?重複比對我的程式碼和文章中程式碼的區別,試了幾個地方,最後發現和其他地方都沒有關係,原因出在<form id="form1" runat="server" enctype="multipart/form- data"> 的enctype屬性上,VS 2005建置的頁面裡沒有這個屬性,而文章實例裡有,我後來加上enctype="multipart/form-data"後System.Web.HttpContext.Current.Request.Files就能z正常取得文件個數了。
大概是VS 2003建置的頁面預設有這個屬性吧,否則這麼重要的屬性作者應該會在文章中提到的。
我做的試驗程式碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo._Default" %>
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<script language="JavaScript">
function addFile()
{
var str = '<INPUT type="file" size="50" NAME="File">'
document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
}
</script>
<html xmlns=" http://www.w3.org/1999/xhtml " >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<input type="button" value="增加(Add)" onclick="addFile()">
<input onclick="this.form.reset()" type="button" value="重置(ReSet)">
<asp:Button Runat="server" Text="上傳" ID="Upload" OnClick="Upload_Click1" ></asp:Button>
<div id="MyFile">
<input type="file" name="File" />
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace Demo
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Upload_Click1(object sender, EventArgs e)
{
HttpFileCollection _files = System.Web.HttpContext.Current.Request.Files;
for (int i = 0; i < _files.Count; i++)
{
_files[i].SaveAs(Server.MapPath("~/Files/" + _files[i].FileName));
}
}
}
}
http://bg5sbk.cnblogs.com/archive/2006/06/11/mulitfileuploadtest.html