在做Web項目時,上傳文件是經常會碰到的需求。ASP.Net的WebForm開發模式中,封裝了FileUpload控件,可以方便的進行文件上傳操作。但有時,你可能不希望使用ASP.Net中的服務器控件,僅僅使用Input標簽來實現文件上傳。當然也是可以的。下面總結在項目中使用過的上傳文件的方式。
一、使用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" />
1 protected void FileUploadButton_Click(object sender, EventArgs e) 2 { 3 if (MyFileUpload.HasFile) 4 { 5 string filePath = Server.MapPath("~/UploadFiles/"); 6 string fileName = MyFileUpload.PostedFile.FileName; 7 MyFileUpload.SaveAs(filePath + fileName); 8 Response.Write("<p >上傳成功!</p>"); 9 } 10 else 11 { 12 Response.Write("<p >請選擇要上傳的文件!</p>"); 13 } 14 }
當然,在實際項目中就不能這么簡單的保存文件了。你至少得增加一些文件類型的判斷,防止用戶上傳一些能夠威脅到系統安全的文件。你可以采用客戶端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" />
1 protected void InputFileUploadButton_Click(object sender, EventArgs e) 2 { 3 HttpFileCollection files = Request.Files; 4 string filePath = Server.MapPath("~/UploadFiles/"); 5 if (files.Count != 0) 6 { 7 string fileName = files[0].FileName; 8 files[0].SaveAs(Path.Combine(filePath, fileName)); 9 Response.Write("<p>上傳成功</p>"); 10 } 11 else 12 { 13 Response.Write("<p>未獲取到Files:"+ files.Count.ToString()+"</p>"); 14 } 15 }
以這種方式進行上傳的時候,好處就是可以方便的用JS生成多個Input標簽來上傳多個文件。且此時需要注意的是,Input標簽必須要有name屬性。在后台,只需要循環調用SaveAs()方法即可。
接下來的兩種上傳方式(二和三)都會用到Ajax異步提交數據,后台使用一個.ashx文件進行處理。兩種方式共用一個文件,ajax傳入的url參數中加一個method來區分哪種方式傳過來的。后台代碼如下:
1 public void ProcessRequest(HttpContext context) 2 { 3 string method = context.Request.QueryString["method"].ToString(); 4 switch (method) 5 { 6 case "ajaxFileUpload": 7 ajaxFileUpload(context); 8 break; 9 case "formDataUpload": 10 formDataUpload(context); 11 break; 12 default: 13 break; 14 } 15 } 16 17 private static void formDataUpload(HttpContext context) 18 { 19 HttpFileCollection files = context.Request.Files; 20 21 string msg = string.Empty; 22 string error = string.Empty; 23 if (files.Count > 0) 24 { 25 files[0].SaveAs(ConfigurationManager.AppSettings["FilePath"].ToString() + System.IO.Path.GetFileName(files[0].FileName)); 26 msg = " 成功! 文件大小為:" + files[0].ContentLength; 27 string res = "{ error:'" + error + "', msg:'" + msg + "'}"; 28 context.Response.Write(res); 29 context.Response.End(); 30 } 31 } 32 33 private static void ajaxFileUpload(HttpContext context) 34 { 35 HttpFileCollection files = context.Request.Files; 36 37 string msg = string.Empty; 38 string error = string.Empty; 39 if (files.Count > 0) 40 { 41 files[0].SaveAs(ConfigurationManager.AppSettings["FilePath"].ToString() + System.IO.Path.GetFileName(files[0].FileName)); 42 msg = " 成功! 文件大小為:" + files[0].ContentLength; 43 string res = "{ error:'" + error + "', msg:'" + msg + "'}"; 44 context.Response.Write(res); 45 context.Response.End(); 46 } 47 }
二、使用Html中的Input標簽加FormData對象實現
使用這種方式上傳附件,對瀏覽器有些要求。FormData屬於Html5中新增的特性,IE瀏覽器只有在10以上才支持。所以,個中利弊自己權衡,但用起來覺得方便。下面直接上代碼:
1 function formDataUpload() { 2 var fileupload = document.getElementById('fileToUpload').files; 3 var formdata = new FormData(); 4 formdata.append('files', fileupload[0]); 5 var xmlHttp = new XMLHttpRequest(); 6 xmlHttp.open("post", 'Handlers/FileUpload.ashx?method=formDataUpload'); 7 xmlHttp.onreadystatechange = function () { 8 if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { 9 alert('上傳成功'); 10 } 11 } 12 xmlHttp.send(formdata); 13 }
三、使用Jquery中的ajaxfileupload.js插件實現上傳
使用此方法,需要引用jquery.js和ajaxfileupload.js兩個文件。還需要注意的部分是兩個文件的版本匹配問題,可能在使用過程中會出現些異常。此時發揮搜索引擎的作用,總能找到你需要的解決方案。
JavaScript代碼如下:
1 function ajaxFileUpLoad() { 2 $.ajaxFileUpload( 3 { 4 url: 'Handlers/FileUpload.ashx?method=ajaxFileUpload', 5 secureuri: false, 6 fileElementId: 'fileToUpload', 7 dataType: 'json', 8 success: function (data, status) { 9 $('#img1').attr("src", data.imgurl); 10 if (typeof (data.error) != 'undefined') { 11 if (data.error != '') { 12 alert(data.error); 13 } else { 14 alert(data.msg); 15 } 16 } 17 }, 18 error: function (data, status, e) { 19 alert(e); 20 } 21 } 22 ) 23 return false; 24 }
Html頁面上的代碼如下:
1 <html xmlns="http://www.w3.org/1999/xhtml"> 2 <head> 3 <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script> 4 <script type="text/javascript" src="Scripts/ajaxfileupload.js"></script> 5 <script type="text/javascript"> 6 $(function () { 7 $("#ajaxfileuploadButton").click(function () { 8 ajaxFileUpLoad(); 9 }) 10 11 $("#formdataButton").click(function () { 12 formDataUpload(); 13 }) 14 }); 15 16 </script> 17 <title></title> 18 <script type="text/javascript"> 19 20 </script> 21 </head> 22 <body> 23 <input type="file" id="fileToUpload" name="fileToUpload" /> 24 <input type="button" id="ajaxfileuploadButton" value="ajaxfileupload插件上傳" /> 25 <input type="button" id="formdataButton" value="FormData方式上傳" /> 26 </body> 27 </html>
總結
以上總結了幾種上傳文件的方式,也簡單的說明了一些使用中需要注意的問題。當然,可能遇到的問題還不止這些,如果在開發過程中還遇到了其他稀奇古怪的問題,可自行搜索相關問題。每一次針對遇到的問題的解決,都是對這方面的知識一次更深入的理解。在不斷解決問題中慢慢進步。
Extension MIME Type
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.sldx application/vnd.openxmlformats-officedocument.presentationml.slide
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.xlsm application/vnd.ms-excel.addin.macroEnabled.12
.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12
---------------------
作者:scanklm
來源:CSDN
原文:https://blog.csdn.net/sxg0205/article/details/48731031
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!