相較於以前使用的上傳空間的優勢:支持html5,不用再安裝flash插件,沒有大小限制,分片之後上傳,上傳之後再進行合併。javascript
前端js代碼css
<script type="text/javascript"> var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../../"; var GUID = WebUploader.Base.guid();//一個GUID $(function () { var $ = jQuery; var uploader = WebUploader.create({ // 選完文件後,是否自動上傳。 auto: false, // swf文件路徑 swf: applicationPath + './Content/Scripts/webuploader/Uploader.swf', // 文件接收服務端。 server: applicationPath + '/QuotationModule/PQuotation_Offer/Upload', // 選擇文件的按鈕。可選。 // 內部根據當前運行是建立,多是input元素,也多是flash. pick: '#uploadify', chunked: true,//開始分片上傳 chunkSize: 2048000,//每一片的大小 formData: { guid: GUID //自定義參數,待會兒解釋 }, // 不壓縮image, 默認若是是jpeg,文件上傳前會壓縮一把再上傳! resize: false }); // 當有文件被添加進隊列的時候 uploader.on('fileQueued', function (file) { //$list.append('<div id="' + file.id + '" class="item">' + // '<h4 class="info">' + file.name + '</h4>' + // '<p class="state">等待上傳...</p>' + // '</div>'); //alert(11); var name = file.name; //文件名 var type = fileType(file.name); //文件類型,獲取的是文件的後綴 var volume = bytesToSize(file.size); //文件大小格式化 document.getElementById("tt").style.display = "block"; document.getElementById("tt").innerHTML = name + type + "等待上傳。。。"; //var oTr = $("<tr></tr>"); //var str = '<td><cite title="' + name + '">' + name + '</cite></td>'; //str += '<td>' + type + '</td>'; //str += '<td>' + volume + '</td>'; //str += '<td id="jintutiao">'; //str += '<span id="baifenbi"></span>0%'; //str += '</td>'; //str += '<td id="uploding">等待上傳</td>'; //$(".fileList").html(str) }); var aa = 1; // 文件上傳過程當中建立進度條實時顯示。 uploader.on('uploadProgress', function (file, percentage) { //var $li = $('#' + file.id), // $percent = $li.find('.progress .progress-bar'); //// 避免重複建立 //if (!$percent.length) { // $percent = $('<div class="progress progress-striped active">' + // '<div class="progress-bar" role="progressbar" style="width: 0%">' + // '</div>' + // '</div>').appendTo($li).find('.progress-bar'); //} //$li.find('p.state').text('上傳中'); //$("#uploding").html("上傳中"); //$percent.css('width', percentage * 100 + '%'); //if (percentage == 1) { // aa++; //} //if (aa <= 2) { // var shuzi = percentage * 100; // $("#baifenbi").html(shuzi.toFixed(2)); //} }); // 文件上傳成功,給item添加成功class, 用樣式標記上傳成功。 uploader.on('uploadSuccess', function (file, response) { //$('#' + file.id).find('p.state').text('已上傳'); $.post('/QuotationModule/PQuotation_Offer/Merge', { guid: GUID, fileName: file.name }, function (data) { //console.log(data); //alert(data.filepath); alert("上傳成功!"); Loading(false, "文件上傳中!"); var address = data.filepath; $("#attach").val(data.filepath); $("#attachName").val(data.fileName); //alert($("#offerAttach").val()); address = address.replace('~', '../../../../'); document.getElementById("tt").style.display = "block"; document.getElementById("tt").innerHTML = "<a href=\"" + address + "\" download=\"" + data.fileName + "\">" + data.fileName + "</a>"; }); }); // 文件上傳失敗,顯示上傳出錯。 uploader.on('uploadError', function (file) { alert('上傳出錯'); }); // 完成上傳完了,成功或者失敗,先刪除進度條。 uploader.on('uploadComplete', function (file) { //$('#' + file.id).find('.progress').fadeOut(); }); //全部文件上傳完畢 uploader.on("uploadFinished", function () { //提交表單 }); //開始上傳 $("#ctlBtn").click(function () { Loading(true, "文件上傳中!"); uploader.upload(); }); }); //字節大小轉換,參數爲b function bytesToSize(bytes) { var sizes = ['Bytes', 'KB', 'MB', 'G']; if (bytes == 0) return 'n/a'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i]; }; //經過文件名,返回文件的後綴名 function fileType(name) { var nameArr = name.split("."); return nameArr[nameArr.length - 1].toLowerCase(); } </script>
後臺的C#代碼html
[HttpPost] public ActionResult Upload() { string fileName = Request["name"]; string fileRelName = fileName.Substring(0, fileName.LastIndexOf('.'));//設置臨時存放文件夾名稱 int index = Convert.ToInt32(Request["chunk"]);//當前分塊序號 var guid = Request["guid"];//前端傳來的GUID號 var dir = Server.MapPath("~/Upload");//文件上傳目錄 dir = Path.Combine(dir, fileRelName);//臨時保存分塊的目錄 if (!System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir); string filePath = Path.Combine(dir, index.ToString());//分塊文件名爲索引名,更嚴謹一些能夠加上是否存在的判斷,防止多線程時併發衝突 var data = Request.Files["file"];//表單中取得分塊文件 string extension = data.FileName.Substring(data.FileName.LastIndexOf(".") + 1, (data.FileName.Length - data.FileName.LastIndexOf(".") - 1));//獲取文件擴展名 //if (data != null)//爲null多是暫停的那一瞬間 //{ data.SaveAs(filePath + fileName); //} return Json(new { erron = 0 });//Demo,隨便返回了個值,請勿參考 } public ActionResult Merge() { var guid = Request["guid"];//GUID var uploadDir = Server.MapPath("~/Upload");//Upload 文件夾 var fileName = Request["fileName"];//文件名 string fileRelName = fileName.Substring(0, fileName.LastIndexOf('.')); var dir = Path.Combine(uploadDir, fileRelName);//臨時文件夾 var files = System.IO.Directory.GetFiles(dir);//得到下面的全部文件 string fileGuid = CommonHelper.GetGuid; string extension = fileName.Substring(fileName.LastIndexOf(".") + 1, (fileName.Length - fileName.LastIndexOf(".") - 1));//獲取文件擴展名 string uploadDate = DateTime.Now.ToString("yyyyMMdd"); //string UserId = ManageProvider.Provider.Current().UserId; string virtualPath = string.Format("~/Resource/Document/NetworkDisk/{0}/{1}/{2}{3}", "Offer", uploadDate, fileGuid, "."+extension); var finalPath = Server.MapPath(virtualPath);//最終的文件名(demo中保存的是它上傳時候的文件名,實際操做確定不能這樣) //建立文件夾,保存文件 string path = Path.GetDirectoryName(finalPath); Directory.CreateDirectory(path); var fs = new FileStream(finalPath, FileMode.Create); foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序,保證從0-N Write { var bytes = System.IO.File.ReadAllBytes(part); fs.Write(bytes, 0, bytes.Length); bytes = null; System.IO.File.Delete(part);//刪除分塊 } fs.Flush(); fs.Close(); System.IO.Directory.Delete(dir);//刪除文件夾 return Json(new { filepath = virtualPath, fileName = fileRelName });//返回文件存儲的路徑,以及文件原來的名稱 }