1. 程式人生 > 實用技巧 >js分段上傳檔案

js分段上傳檔案

JS端。檔案過大,開始使用了壓縮檔案後上傳。後面改為分段上傳,壓縮檔案部分沒有做對應修改。

       jx: function () {

                if (!$("#SearchForm").form('validate')) {
                    return false;
                }
                var filepath = $("#importExcel").val().trim();
                var laststr = filepath.substr(filepath.lastIndexOf("
.")); if (filepath == "") { $.messager.alert('提示資訊', '請選擇要匯入的檔案!'); return; } else if (laststr != ".xls" && laststr != ".xlsx") { $.messager.alert('提示資訊', '檔案型別傳入錯誤,請選擇Excel檔案!');
return; } //var formData = new FormData(); //formData.append("fileName", document.getElementById("importExcel").files[0].fileName); $.messager.progress({ 'text': '載入中', showType: 'fade' });//呼叫前開啟 var excelFile = document.getElementById("
importExcel").files[0]; var reader = new FileReader(); reader.readAsDataURL(excelFile); reader.onload = function () { var start = "data:application/vnd.ms-excel;base64,";//獲得字串的開始位置 var strBase64 = reader.result.substring(start.length); var zip = new JSZip(); // 向zip檔案中新增圖片,可以新增多個檔案或者圖片,此處以圖片為例 // base64圖片需要去掉base64圖片標識 zip.file(excelFile.name, strBase64, { base64: true }); zip.generateAsync({ type: "base64", // 壓縮型別 compression: "DEFLATE", // STORE:預設不壓縮 DEFLATE:需要壓縮 compressionOptions: { level: 9 // 壓縮等級1~9 1壓縮速度最快,9最優壓縮方式 // [使用一張圖片測試之後1和9壓縮的力度不大,相差100位元組左右] } }).then(function (content) { var allSize = content.length; var fromSize = 0; var ToSize = 0; var updSize = 50 * 1024; var paga = parseInt(((parseInt(allSize) / parseInt(updSize)) + 1)); var isOver = false; var isAsync = false;//最後一次用非同步處理 var txtFileName = new Date().getTime() + ".txt"; $.messager.progress({ 'text': '載入中', showType: 'fade' });//呼叫前開啟 for (var i = 0; i < paga; i++) { fromSize = i * updSize; ToSize = (i + 1) * updSize; if ((parseInt(fromSize) + parseInt(updSize)) > parseInt(allSize)) { isOver = true; isAsync = true; ToSize = allSize; } var blobcontent = content.slice(fromSize, ToSize); // 壓縮的結果為blob型別(二進位制流),可用作檔案上傳 $.ajax({ url: "/EKBMS/PrdctPlansUpload/ImportLoan1026", async: isAsync,//預設是true:非同步,false:同步。 type: 'POST', data: { "fileExcelName": excelFile.name, "strBase64": blobcontent, "isOver": isOver, "txtFileName": txtFileName, "IndexCtn": i }, //data: { "fileExcelName": excelFile.name, "strBase64": blobcontent }, beforeSend: function () { //$.messager.progress({ 'text': '載入中', showType: 'fade' });//呼叫前開啟 }, success: function (res) { if (!isOver) return; if (res.Result) { document.getElementById("ImportLoanform").reset(); $('#export').dialog('close') $.messager.progress('close');//回撥後關閉 var Msg = res.Msg; $.messager.alert('提示資訊', Msg); //匯入成功後重新整理頁面資料 GetData(); } else { $.messager.progress('close');//回撥後關閉 //執行解析失敗 var Msg = res.Msg; $.messager.alert('提示資訊 ', Msg); //$("#SearchForm")[0].reset(); } }, complete: function () { if (!isOver) return; $.messager.progress('close');//回撥後關閉 }, error: function (er) { if (!isOver) return; $.messager.progress('close');//回撥後關閉 $.messager.alert('提示資訊', '操作失敗!'); // $("#SearchForm")[0].reset(); } }); if (isOver) break; } }); }; reader.onerror = function (ex) { console.log("上傳失敗", ex) } //var xhr = new XMLHttpRequest(); ////post方式,url為伺服器請求地址,true 該引數規定請求是否非同步處理。 //xhr.open("post", "/PrdctPlansUpload/ImportLoan", true); ////請求完成 //xhr.onload = this._uploadComplete; ////請求失敗 //xhr.onerror = this._uploadFailed; ////開始上傳,傳送form資料 //xhr.send(formData); },

Controller端

        /// <summary>
        /// 匯入EXCLE
        /// </summary>
        /// <param name="importExcel"></param>
        /// <returns></returns>
        public JsonResult ImportLoan1026(string fileExcelName, string strBase64, bool isOver, string txtFileName, int IndexCtn)
        {

            //_Service.AddSysLog(ModuleCode.PrdctPlansUpload, OperateCode.Import, LogFlag.INFO, "進入方法ImportLoan成功!操作者:" + LoginUser.UserNo + "檔案是否為空" + (importExcel == null).ToString(), null);

            string FilePath;


            FilePath = Server.MapPath("~/Excel") + "\\" + txtFileName;
            if (IndexCtn == 0)
            {
                System.IO.File.Create(FilePath).Close();
            }
            //寫入內容
            FileStream fs = new FileStream(FilePath, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(strBase64);
            sw.Close();
            fs.Close();


            //如果不是最後一個,則在系統存一個零時txt,儲存內容
            if (!isOver)
            {  
                return Json(new ResultPageModel<PrdctPlansImportModelVM> { Result = false, rows = null, Msg = "繼續上傳!" });
            }


            //讀取檔案  
            strBase64 = string.Empty;
            FilePath = Server.MapPath("~/Excel") + "\\" + txtFileName; 
            StreamReader sr = new StreamReader(FilePath, Encoding.Default);
            String line;
            while ((line = sr.ReadLine()) != null)
            {

                strBase64=strBase64+line.ToString(); 
            }
            sr.Close(); 

            List<PlanAllONE> lstPlan = new List<PlanAllONE>();
            PlanAllVM _PlanAllVM = new PlanAllVM();
            bool _IsSuc = true;
            string _Msg = string.Empty;
            List<PrdctPlansImportModelVM> LisPrdctPlan = new List<PrdctPlansImportModelVM>();
            try
            {

                if (string.IsNullOrEmpty(strBase64))
                {
                    RespModel.WarningResult("上傳的檔案不能為空");
                    //return Json(RespModel, "text/html", JsonRequestBehavior.AllowGet);
                    return Json(RespModel);
                }

                //將字串轉換為byte陣列
                byte[] bytes = Convert.FromBase64String(strBase64);
                var filePath = Server.MapPath("~/Excel");
                var fileName_Zip = filePath + "\\" + fileExcelName.Substring(0, fileExcelName.IndexOf(".")) + ".Zip";
                Bytes2File(bytes, filePath, fileExcelName);
                var fileName_Excel = string.Empty;
                //解壓   
                UnpackFiles(fileName_Zip, filePath + "\\ExcelXLS", ref fileName_Excel);

                // 開啟檔案
                FileStream fileStream = new FileStream(fileName_Excel, FileMode.Open, FileAccess.Read, FileShare.Read);
                // 讀取檔案的 byte[]
                byte[] bytes_New = new byte[fileStream.Length];
                fileStream.Read(bytes_New, 0, bytes_New.Length);
                fileStream.Close();
                // 把 byte[] 轉換成 Stream
                Stream stream = new MemoryStream(bytes_New);
                //刪除檔案
                ExcelDel(fileName_Zip);
                ExcelDel(fileName_Excel);
                ExcelDel(FilePath);

               
                return Json(new ResultPageModel<PrdctPlansImportModelVM> { Result = _IsSuc, rows = LisPrdctPlan, Msg = _Msg });
                //return Json(new ResultPageModel<PrdctPlansImportModelVM> { Result = _IsSuc, rows = LisPrdctPlan, Msg = _Msg }, "text/html", JsonRequestBehavior.AllowGet);
            }

            catch (Exception ex)
            {
                _Service.AddSysLog(ModuleCode.PrdctPlansUpload, OperateCode.Import, LogFlag.ERROR, "匯入的模板格式不正確,資料異常!", ex);
                //return Json(new ResultPageModel<PrdctPlansImportModelVM> { Result = false, rows = LisPrdctPlan, Msg = "匯入異常!" }, "text/html", JsonRequestBehavior.AllowGet);
                return Json(new ResultPageModel<PrdctPlansImportModelVM> { Result = false, rows = LisPrdctPlan, Msg = "匯入異常!" });
            }


        }