上傳文件算是比較常規的一個功能,Asp.Net自帶了一個上傳控件 FileUpload ,簡單易用但是體驗不太好,所有開發者經常都會選擇一個JS插件來進行上傳,比如:Uploadify SWFupload 等等...
如果沒有特別高的要求,也可以自已實現無刷新有等待效果的上傳...
目錄 |
知識了解 |
表單提交后,在一般處理程序中HttpContext.Current.Request.Files才能獲取客戶端上傳文件集合
http://www.malsup.com/jquery/form/#api
提交表單,上傳時,等待效果可以在beforeSubmit回調函數中顯示
http://www.malsup.com/jquery/form/#options-object
那么還要需要設置form的enctype屬性,enctype默認為:application/x-www-form-urlencoded,
但是表單中含有上傳控件時,enctype屬性必須使用:multipart/form-dat,否則得到不客戶端上傳文件集合。
值 | 描述 |
application/x-www-form-urlencoded | 在發送前編碼所有字符(默認) |
multipart/form-data | 不對字符編碼。在使用包含文件上傳控件的表單時,必須使用該值。 |
text/plain | 空格轉換為 "+" 加號,但不對特殊字符編碼。 |
更多相關:
http://www.w3school.com.cn/tags/att_form_enctype.asp
http://msdn.microsoft.com/zh-cn/library/system.web.httprequest.files(v=VS.80).aspx
默認大小為4096K,也就是4M; 如果大小超過限制會引發一個 ConfigurationErrorsException 異常; 對於圖片上傳來說4M基本能滿足,但是對於文件上傳來說,4M的最大上傳限制明顯不夠;
這樣就需自定義最大上傳限制,我們可以通過修改Web.config文件中的httRuntime元素中的maxRequestLength元素
<system.web> <httpRuntime maxRequestLength="2097151" executionTimeout="3600"/> </system.web>
maxRequestLength元素雖然可以自定義設置,但是最大也不能超過2097151KB(最大不能大於2G)
可以看到還設置了executionTimeout元素, executionTimeout元素表示請求允許被執行的秒數,默認為110秒(.Net Framework1.1 時默認為:90秒);
當上傳文件越大,執行請求的時間也就越長,所以根據設置的maxRequestLengtht適當的調整executionTimeout元素的值(單位為:秒)。
更多httRuntime 相關:
http://msdn.microsoft.com/zh-cn/library/e1f13641(v=vs.90).aspx
前后端實現代碼 |
.aspx頁中代碼

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FileUploadSample._Default" %> <!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 runat="server"> <title>Porschev--Asp.Net 使用Jquery和一般處理程序實現無刷新上傳大文件</title> <link href="!css/style.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server" enctype="multipart/form-data"> <div class="carea"> <div class="ui-tabs-panel"> <div class="search_head"> <h3 class="sh_title"> Porschev--Asp.Net 使用Jquery和一般處理程序實現無刷新上傳大文件</h3> </div> <ul class="info_input"> <li><b>選擇文件:</b> <div class="ii_conarea"> <input id="fulFile" name="fulFile" type="file" class="ful" /> <img id="imgUploading" src="!images/uploading.gif" alt="正在上傳..." class="loading_img none" /> </div> </li> </ul> <input id="btnSubmit" type="button" value="上傳" class="btn_sub" /> </div> </div> </form> </body> </html> <script src="!js/jquery-1.7.2.min.js" type="text/javascript"></script> <script src="!js/jquery.form.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { $("#btnSubmit").click(function() { if ($("[id$='fulFile']").val() == "") { alert("請選擇要上傳的文件!"); return false; } $("[id$='form1']").ajaxSubmit({ url: "Handler/UploadHandler.ashx", type: "post", dataType: "text", resetForm: "true", beforeSubmit: function() { $("[id$='fulFile']").hide(); $("[id$='imgUploading']").show(); $("[id$='btnSubmit']").hide(); }, success: function(msg) { $("[id$='fulFile']").show(); $("[id$='imgUploading']").hide(); $("[id$='btnSubmit']").show(); if (msg == "1") { alert("上傳成功!"); } else if (msg == "-2") { alert("禁止上傳 0 KB大小的文件!"); } else if (msg == "-1") { alert("請選擇要上傳的文件!"); } else if (msg == "-0") { alert("上傳失敗!"); } return false; }, error: function(jqXHR, errorMsg, errorThrown) { $("[id$='fulFile']").show(); $("[id$='imgUploading']").hide(); $("[id$='btnSubmit']").show(); alert("錯誤信息:" + errorMsg); return false; } }); }); }); </script>
一般處理程序中代碼

using System; using System.IO; using System.Web; using System.Web.Services; namespace FileUploadSample.Handler { /// <summary> /// Summary description for $codebehindclassname$ /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class UploadHandler : IHttpHandler { /// <summary> /// 上傳文件夾 /// </summary> private const string UPLOAD_FOLDER = "~/UploadFile/"; public void ProcessRequest(HttpContext context) { int resultVal = (int)ReturnVal.Failed; try { HttpPostedFile myFile = context.Request.Files["fulFile"]; if (myFile != null) { if (myFile.InputStream.Length != 0) { string originalFileName = Path.GetFileName(myFile.FileName); //原文件名 string newFileName = string.Format("{0}_{1}", Guid.NewGuid(), originalFileName); //新文件名---組成形式: GUID + 下划線 + 原文件名 string fileAbsPath = context.Server.MapPath(UPLOAD_FOLDER) + newFileName; //絕對路徑 myFile.SaveAs(fileAbsPath); resultVal = (int)ReturnVal.Succeed; } else { resultVal = (int)ReturnVal.FileEmpty; } } else { resultVal = (int)ReturnVal.NotSelected; } } catch (Exception) { resultVal = (int)ReturnVal.Failed; } finally { context.Response.Write(resultVal); } } #region## 返回值 /// <summary> /// 返回值 /// </summary> private enum ReturnVal : int { /// <summary> /// 不能上傳 0 K大小的文件 /// </summary> FileEmpty = -2, /// <summary> /// 未選中文件 /// </summary> NotSelected = -1, /// <summary> /// 上傳失敗 /// </summary> Failed = 0, /// <summary> /// 成功 /// </summary> Succeed = 1 } #endregion public bool IsReusable { get { return false; } } } }
實現截圖 |
常見問題 |
- 無法獲取客戶端上傳的文件,一般有三種情況
- 頁面上沒有 type="file" 標簽
- form的enctype屬性未設置成multipart/form-data
- 提交方法有問題,請注意JS源碼中提交表單的ajaxSubmit方法 (Jquery.form.js 需要依賴於jquery.js)
源碼下載 |
示例下載:http://files.cnblogs.com/zhongweiv/FileUploadSample.zip
示例代碼Target Framework為:.NET Framework3.5^_^!