基於.NET平臺實現文件上傳插件有不少種,jquery.upload.js、ajaxFileUpload.js、SWFUpload.js、WebUploader.JS。實際項目中配置簡單,後期可維護性好的,建議採用ajaxFileUpload.js,缺點是上傳文件功能單一,實現上傳完成度顯示須要集成UploadProcess.JS截獲上傳進度,且沒法實現分段上傳。WebUploader.js實現了全部的功能,且性能較優,下面介紹該空間實現分段上傳及完成度顯示實例。css
頁面引用添加webuploader.css和webuploader.js,頁面添加上傳按鈕元素,建議用div、p等換行標籤,增長Id屬性,頁面添加結構以下:html
參數index爲自定義變量,保證當前頁面存在多個上傳按鈕時便於區分。頁面初始化定義代碼以下:前端
uploadfilefun(o)爲自定義封裝JS函數;定義代碼以下:jquery
1 //上傳文檔、視頻 2 function uploadfilefun(o) { 3 var fb_ipt = $(o).find('.file-box >div').eq(0).attr('id'); 4 var guid = new GUID().newGuid(); 5 var uploader = WebUploader.create({ 6 auto: true, 7 swf: '/Scripts/webuploader/Uploader.swf', 8 server: '/superadmin/CourseSuper/ChunkUploadFile', 9 pick: { 10 id: '#' + fb_ipt, 11 multiple: false 12 }, 13 fileSingleSizeLimit: 500 * 1024 * 1024, //設定單個文件大小(bit) 14 resize: false, 15 chunked: true,//分片上傳-大文件的時候分片上傳,默認false 16 chunkSize: 1024 * 1024, 17 formData: { 18 guid: guid//自定義參數 19 }, 20 ///上傳格式 21 accept: { 22 title: 'file limit', 23 extensions: 'xls,xlsx,doc,docx,ppt,pptx,pdf,mp4,swf,jpg,png', 24 } 25 }) 26 var up_div = $(o).find('.upload'); 27 var up_status = $(up_div).find('.upload-status'); 28 uploader.on('uploadProgress', function (file, percentage) { 29 $(up_div).addClass('selected'); 30 var nowSize = 0;//已上傳大小 31 var gb = Math.pow(1024, 3); 32 var mb = Math.pow(1024, 2); 33 var kb = 1024; 34 var fileSize = uploader.getFiles()[uploader.getFiles().length - 1].size;//總大小 35 if (fileSize >= gb) { 36 Size = (fileSize / gb).toFixed(0) + "GB"; 37 } 38 else if (fileSize >= mb) { 39 Size = (fileSize / mb).toFixed(0) + "MB"; 40 } 41 else if (fileSize >= kb) { 42 Size = (fileSize / kb).toFixed(0) + "KB"; 43 } 44 else { 45 Size = fileSize + "B"; 46 } 47 $(up_status).addClass('i').removeClass('s f'); 48 $(up_status).find('i').html((percentage * 100).toFixed(0) + "%");//已上傳比例 49 $(up_div).find('.file-size').html("共" + Size);//總大小 50 }); 51 uploader.on('uploadSuccess', function (file, response) { 52 $(up_div).find('input[name=Suffix]').val(response.Suffix); 53 var linkSelector = $(up_div).find('input[name=LinkResourceName]'); 54 linkSelector.val(response.Name); 55 linkSelector.blur(); 56 limitLinkResource(linkSelector, 30); 57 if (response.Status == 1) { 58 ///文件合併 59 $.post("/superadmin/coursesuper/merge", { "guid": guid, "suffix": response.Suffix }, function (data) { 60 if (data.Status==1) { 61 $(up_status).addClass('s').removeClass('i f'); 62 $(up_div).find('input[name=LinkResource]').val(data.fileGuid); 63 } 64 else { 65 $(up_status).addClass('f').removeClass('i s'); 66 } 67 }) 68 } 69 else { 70 $(up_status).addClass('f').removeClass('i s'); 71 } 72 uploader.removeFile(file); 73 uploader.reset(); 74 }); 75 76 uploader.on('uploadError', function (file, reason) { 77 $(up_status).addClass('f').removeClass('i s'); 78 uploader.removeFile(file); 79 uploader.reset(); 80 }); 81 uploader.on("uploadFinished", function () { 82 uploader.destroy(); 83 uploadfilefun(o); 84 }); 85 uploader.on("error", function (type) { 86 if (type == "Q_TYPE_DENIED") { 87 showMessage('請上傳Word,Excel,MP4,SWF,PDF,PPT,JPG,PNG格式文件!', "428px", "70px"); 88 } else if (type == "F_EXCEED_SIZE") { 89 showMessage('文件大小不能超過500MB!', "328px", "70px"); 90 } else { 91 showMessage("服務器出錯!請檢查後從新上傳。", "362px", "70px"); 92 } 93 }); 94 return uploader; 95 }
分段上傳配置注意事項:web
1.Create()方法配置Chunked:true;表示以分段方式上傳ajax
2.Chunksize:1024*1024;分段的大小,建議不要太小或過大,網絡容許的狀況1M是能夠的後端
3.formData:{guid:guid},自定義GUID編碼服務器
4.uploadSuccess()方法定義回調函數,實現分段文件合併網絡
文件分段上傳後端編碼:函數
/// <summary> /// 分段上傳課程資源 /// </summary> /// <returns></returns> public ActionResult ChunkUploadFile() { int chunks = Convert.ToInt32(Request["chunks"]); int index = Convert.ToInt32(Request["chunk"]);//當前分塊序號 var guid = Request["guid"];//前端傳來的GUID號 var dir = string.Format("{0}Upload\\CourseResource\\{1}", WebConfigInfo.PhysicalApplicationPath,guid); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } string filePath = Path.Combine(dir, index.ToString()); HttpFileCollection file_upload = System.Web.HttpContext.Current.Request.Files; var name = Path.GetFileNameWithoutExtension(file_upload[0].FileName); var fileExtension = Path.GetExtension(file_upload[0].FileName); var fileName = Guid.NewGuid().ToString() + fileExtension; file_upload[0].SaveAs(filePath); return Json(new { Status = 1, Name = name, Suffix = fileExtension }); }
上傳成功後回調函數執行文件合併,代碼以下:
/// <summary> /// 合併分段文件 /// </summary> /// <returns></returns> public ActionResult Merge() { var guid = Request["guid"]; var uploadDir = string.Format("{0}Upload\\CourseResource",WebConfigInfo.PhysicalApplicationPath); var dir = Path.Combine(uploadDir, guid);//臨時文件夾 var fileExtension = Request["suffix"]; var fileName = Guid.NewGuid().ToString() + fileExtension; try { var files = System.IO.Directory.GetFiles(dir);//得到guid下全部文件 var finalPath = Path.Combine(uploadDir, fileName);//最終的文件名 var fs = new FileStream(finalPath, FileMode.Create); foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排序合併 { var bytes = System.IO.File.ReadAllBytes(part); fs.Write(bytes, 0, bytes.Length); bytes = null; System.IO.File.Delete(part);//刪除分塊 } fs.Close(); System.IO.Directory.Delete(dir);//刪除文件夾 var fileGuid = string.Format("/Upload/CourseResource/{0}", fileName); return Json(new { Status = 1, fileGuid = fileGuid }); } catch (Exception ex) { return Json(new { Status = 0,Message=ex.Message }); } }