這裡附加一下上傳單個檔案的CS代碼:
protected void upload_Click(object sender, EventArgs e)
{
if (upfile.HasFile)
{
string fname = upfile.PostedFile.FileName;
int fi = fname.LastIndexOf("\\") + 1;
string filename = fname.Substring(fi);
upfile.PostedFile.SaveAs(Server.MapPath("upload\\" + filename));
Response.Write("<script>alert('報名表上傳成功!');</script>");
}
else
{
Response.Write("<script>alert('請選擇您要上傳的報名表!');</script>");
}
}
下面是上傳多個檔案的全部代碼,第一次實現這樣的功能,難免有考慮不周全的地方,還望高手見到後指教!
【顯示頁面代碼】:
在<head></head>標籤中插入如下指令碼代碼:
<script type="text/javascript">
function addfile()
{
var uploadfiles=document.getElementById("uploadfiles"),
str = '<INPUT type="file" size="50" NAME="File">';
uploadfiles.innerHTML+=str;
}
</script>
在頁面主體部分插入:
<div>
<p id="uploadfiles"><input type="file" size="50" name="file"></p>
<input onclick="addfile()" type="button" value="增加">
<asp:button id="uploadbutton" Text="開始上傳" Runat="server"></asp:button>
</div>
【C#代碼】:
添加using指令:using System.Text.RegularExpressions;
在protected void Page_Load(object sender, EventArgs e){}中插入如下代碼:
HttpFileCollection files = HttpContext.Current.Request.Files;
//狀態資訊
System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
for (int ifile = 0; ifile < files.Count; ifile++)
{
HttpPostedFile postedfile = files[ifile];
string filename, fileExt;
filename = System.IO.Path.GetFileName(postedfile.FileName); //擷取檔案名稱
fileExt = System.IO.Path.GetExtension(filename); //擷取檔案尾碼
int MaxAllowUploadFileSize = Convert.ToInt32(System.Configuration.ConfigurationSettings.
AppSettings["MaxAllowUploadFileSize"]); //定義允許上傳檔案大小
if (MaxAllowUploadFileSize == 0) { MaxAllowUploadFileSize = 26500; }
string allowexts = System.Configuration.ConfigurationSettings.AppSettings["AllowUploadFileType"];
//定義允許上傳檔案類型
if (allowexts == "") { allowexts = "doc|docx|rar|xls|xlsx|txt"; }
Regex allowext = new Regex(allowexts);
if (postedfile.ContentLength < MaxAllowUploadFileSize && allowext.IsMatch(fileExt)) //檢查檔案大小及副檔名
{
postedfile.SaveAs(Server.MapPath("upload\\" + filename + fileExt)); //upload為與本頁面同一目錄,可自行修改
}
else
{
Response.Write("<script>alert('不允許上傳類型" + fileExt + "或檔案過大')</script>");
}
}
【Web.config中代碼】:
<appSettings>
<add key="MaxAllowUploadFileSize" value="256000" />
<add key="AllowUploadFileType" value="doc|docx|rar|xls|xlsx|txt" />
</appSettings>