ASP.Net的WebForm開發模式中,封裝了FileUpload控制項,可以方便的進行檔案上傳操作。但有時,你可能不希望使用ASP.Net中的伺服器控制項,僅僅使用Input標籤來實現檔案上傳。當然也是可以的。下面總結在項目中使用過的上傳檔案的方式。
本文我們總結了三種ASP.Net中上傳檔案的方法。
一、使用Asp.Net中的FileUpload伺服器端控制項實現上傳
使用asp.net中的伺服器端控制項FileUpload上傳檔案非常方便。FileUpload對上傳操作進行了封裝,你只需要調用SaveAs方法即可完成上傳。下面是簡單的上傳代碼。
<p>伺服器端控制項上傳</p>
<asp:FileUpload ID="MyFileUpload" runat="server" />
<asp:Button ID="FileUploadButton" runat="server" Text="上傳"
onclick="FileUploadButton_Click" />
protected void FileUploadButton_Click(object sender, EventArgs e)
{
if (MyFileUpload.HasFile)
{
string filePath = Server.MapPath("~/UploadFiles/");
string fileName = MyFileUpload.PostedFile.FileName;
MyFileUpload.SaveAs(filePath + fileName);
Response.Write("<p >上傳成功!</p>");
}
else
{
Response.Write("<p >請選擇要上傳的檔案!</p>");
}
}
當然,在實際項目中就不能這麼簡單的儲存檔案了。你至少得增加一些檔案類型的判斷,防止使用者上傳一些能夠威脅到系統安全的檔案。你可以採用用戶端JS驗證的方式,也能夠在.cs的伺服器端代碼中驗證。
在asp.Net WebForm開發架構下,我們也可以利用Html的Input標籤來上傳檔案。這時候需要注意的一點,這個type為file的Input標籤需要加上runat="server"屬性,否則在後台Request.Files擷取不到上傳的檔案。
<p>使用Html的Input標籤上傳</p>
<input type="file" name="MyFileUploadInput" runat="server" /><asp:Button
ID="InputFileUploadButton" runat="server" Text="上傳"
onclick="InputFileUploadButton_Click" />
protected void InputFileUploadButton_Click(object sender, EventArgs e)
{
HttpFileCollection files = Request.Files;
string filePath = Server.MapPath("~/UploadFiles/");
if (files.Count != 0)
{
string fileName = files[0].FileName;
files[0].SaveAs(Path.Combine(filePath, fileName));
Response.Write("<p>上傳成功</p>");
}
else
{
Response.Write("<p>未擷取到Files:"+ files.Count.ToString()+"</p>");
}
}
以這種方式進行上傳的時候,好處就是可以方便的用JS產生多個Input標籤來上傳多個檔案。且此時需要注意的是,Input標籤必須要有name屬性。在後台,只需要迴圈調用SaveAs()方法即可。
接下來的兩種上傳方式(二和三)都會用到Ajax非同步提交資料,後台使用一個.ashx檔案進行處理。兩種方式共用一個檔案,ajax傳入的url參數中加一個method來區分哪種方式傳過來的。後台代碼如下:
public void ProcessRequest(HttpContext context)
{
string method = context.Request.QueryString["method"].ToString();
switch (method)
{
case "ajaxFileUpload":
ajaxFileUpload(context);
break;
case "formDataUpload":
formDataUpload(context);
break;
default:
break;
}
}
private static void formDataUpload(HttpContext context)
{
HttpFileCollection files = context.Request.Files;
string msg = string.Empty;
string error = string.Empty;
if (files.Count > 0)
{
files[0].SaveAs(ConfigurationManager.AppSettings["FilePath"].ToString() + System.IO.Path.GetFileName(files[0].FileName));
msg = " 成功! 檔案大小為:" + files[0].ContentLength;
string res = "{ error:'" + error + "', msg:'" + msg + "'}";
context.Response.Write(res);
context.Response.End();
}
}
private static void ajaxFileUpload(HttpContext context)
{
HttpFileCollection files = context.Request.Files;
string msg = string.Empty;
string error = string.Empty;
if (files.Count > 0)
{
files[0].SaveAs(ConfigurationManager.AppSettings["FilePath"].ToString() + System.IO.Path.GetFileName(files[0].FileName));
msg = " 成功! 檔案大小為:" + files[0].ContentLength;
string res = "{ error:'" + error + "', msg:'" + msg + "'}";
context.Response.Write(res);
context.Response.End();
}
}
二、使用Html中的Input標籤加FormData對象實現
使用這種方式上傳附件,對瀏覽器有些要求。FormData屬於Html5中新增的特性,IE瀏覽器只有在10以上才支援。所以,個中利弊自己權衡,但用起來覺得方便。下面直接上代碼:
function formDataUpload() {
var fileupload = document.getElementById('fileToUpload').files;
var formdata = new FormData();
formdata.append('files', fileupload[0]);
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", 'Handlers/FileUpload.ashx?method=formDataUpload');
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert('上傳成功');
}
}
xmlHttp.send(formdata);
}
三、使用Jquery中的ajaxfileupload.js外掛程式實現上傳
使用此方法,需要引用jquery.js和ajaxfileupload.js兩個檔案。還需要注意的部分是兩個檔案的版本匹配問題,可能在使用過程中會出現些異常。此時發揮搜尋引擎的作用,總能找到你需要的解決方案。
JavaScript代碼如下:
function ajaxFileUpLoad() {
$.ajaxFileUpload(
{
url: 'Handlers/FileUpload.ashx?method=ajaxFileUpload',
secureuri: false,
fileElementId: 'fileToUpload',
dataType: 'json',
success: function (data, status) {
$('#img1').attr("src", data.imgurl);
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
alert(data.error);
} else {
alert(data.msg);
}
}
},
error: function (data, status, e) {
alert(e);
}
}
)
return false;
}
Html頁面上的代碼如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" src="Scripts/ajaxfileupload.js"></script>
<script type="text/javascript">
$(function () {
$("#ajaxfileuploadButton").click(function () {
ajaxFileUpLoad();
})
$("#formdataButton").click(function () {
formDataUpload();
})
});
</script>
<title></title>
<script type="text/javascript">
</script>
</head>
<body>
<input type="file" id="fileToUpload" name="fileToUpload" />
<input type="button" id="ajaxfileuploadButton" value="ajaxfileupload外掛程式上傳" />
<input type="button" id="formdataButton" value="FormData方式上傳" />
</body>
</html>
總結
以上總結了幾種上傳檔案的方式,也簡單的說明了一些使用中需要注意的問題。當然,可能遇到的問題還不止這些,如果在開發過程中還遇到了其他稀奇古怪的問題,可自行搜尋相關問題。每一次針對遇到的問題的解決,都是對這方面的知識一次更深入的理解。在不斷解決問題中慢慢進步。