文件無刷新上傳並獲取保存到服務器端的路徑
遇到上傳文件的問題,結合之前用到過的swfUpload,又找了一個無刷新上傳文件的jquery插件uploadify,寫篇博客記錄一下分別介紹這兩個插件的實現方法
- swfUpload
- 導入swfUpload的開發包
- 添加js引用,引用swfUpload.js與handler.js文件,如果對swfUpload不了解、有疑問可以看看這篇博客
-
頁面初始化
-
修改handler.js文件中 上傳成功的事件,serverData是服務器端的響應
- Uploadify
- 導入uploadify開發包,從官網下載,官網文檔,中文文檔,官網示例
-
添加js與css的引用,jquery.uploadify.js 、uploadify.css
(注:在css中引用uploadify-cancel.png圖片文件的路徑是可能不正確,可以在uploadify.css文件中自己進行更改)
-
頁面初始化
頁面初始化時,可以指定許多設置,並對上傳成功的事件進行重載,data表示服務器端的響應
- 服務器端上傳處理程序

1 /// <summary> 2 /// 上傳文件 3 /// </summary> 4 public class UploadFileHandler : IHttpHandler, IRequiresSessionState 5 { 6 public void ProcessRequest(HttpContext context) 7 { 8 context.Response.ContentType = "text/plain"; 9 //驗證上傳權限 10 if (context.Session["User"] == null) 11 { 12 context.Response.Write("no permission"); 13 context.Response.End(); 14 return; 15 } 16 try 17 { 18 //獲取上傳文件 19 //Filedata是客戶端已經定義好的,如果想要更改,更改js文件中的配置 20 HttpPostedFile image_upload = context.Request.Files["Filedata"]; 21 //獲取文件擴展名 22 string fileExt = System.IO.Path.GetExtension(image_upload.FileName).ToLower(); 23 //驗證文件擴展名是否符合要求,是否是允許的圖片格式 24 if (!FileTypes.IsAllowed(fileExt)) 25 { 26 return; 27 } 28 //當前時間字符串 29 string timeString = DateTime.Now.ToString("yyyyMMddHHmmssfff"); 30 //保存虛擬路徑構建 31 string path = "/Upload/" + timeString + fileExt; 32 //獲取、構建要上傳文件的物理路徑 33 string serverPath = context.Server.MapPath("~/" + path); 34 //保存圖片到服務器 35 image_upload.SaveAs(serverPath); 36 //輸出保存路徑 37 context.Response.Write(path); 38 } 39 catch (Exception ex) 40 { 41 context.Response.Write("Error"); 42 //記錄日志 43 new Common.LogHelper(typeof(UploadFileHandler)).Error(ex); 44 } 45 } 46 47 public bool IsReusable 48 { 49 get 50 { 51 return false; 52 } 53 } 54 } 55 public static class FileTypes 56 { 57 private static List<string> allowedFileTypes = new List<string>(); 58 //獲取允許json配置文件 59 private static string jsonFilePath = Common.PathHelper.MapPath("~/AllowedFileTypes.json"); 60 61 /// <summary> 62 /// 允許的文件類型 63 /// </summary> 64 public static List<string> AllowedFileTypes 65 { 66 get 67 { 68 return allowedFileTypes; 69 } 70 71 set 72 { 73 allowedFileTypes = value; 74 } 75 } 76 77 /// <summary> 78 /// 靜態構造方法 79 /// </summary> 80 static FileTypes() 81 { 82 LoadFileTypesFromJson(); 83 }