zoukankan      html  css  js  c++  java
  • 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 = "导入异常!" });
                }
    
    
            }
  • 相关阅读:
    近来无聊 写了一个google音乐的下载器
    HTML编辑器 HtmlArea
    Html编辑器 TinyMCE
    IE浏览器自定义地址协议 通过B/S程序中打开C/S程序
    html 元素的 onpropertychange 事件
    asp.net 服务器控件防止重复提交表单
    用 BindingSource 绑定窗体中控件不失去焦点无法更新数据源的问题
    动态创建大量 html dom 元素时提升性能
    很黄的日期格式化。。。
    Asp.net 导出 .html,.txt 等格式的文件
  • 原文地址:https://www.cnblogs.com/lhlong/p/13879016.html
Copyright © 2011-2022 走看看