DotNet结合ajax实现分块上传

原创 Laughing  2019-07-07 09:05  阅读 38 次 评论 0 条

原理就不做介绍了,就是在前段先循环对文件进行分块,然后分别发送到后台,所有分块发送完成后,后台对文件进行合并。

html代码

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <title></title>  
  6.     <link href="../Scripts/layui/css/layui.css" rel="stylesheet" />  
  7.     <link href="../Css/fileUpload.css" rel="stylesheet" />  
  8.     <link href="../Css/UpLoadFile.css" rel="stylesheet" />  
  9.     <link href="../Scripts/layui/layui_exts/dtree/dtree.css" rel="stylesheet" />  
  10.     <link href="../Scripts/layui/layui_exts/dtree/font/dtreefont.css" rel="stylesheet" />  
  11.     <script src="../Scripts/Jquery1.12.4/jquery-1.12.4.min.js"></script>  
  12.     <script src="../Scripts/layui/layui.js"></script>  
  13.     <script src="../JS/plupload.full.min.js" type="text/javascript"></script>  
  14.     <script src="../JS/jquery.base64.js" type="text/javascript"></script>  
  15.     <script src="../Scripts/bootstrap3.3.7/js/bootstrap.js"></script>  
  16.     <link href="../Scripts/bootstrap3.3.7/css/bootstrap.css" rel="stylesheet" />  
  17.     <link href="../Scripts/layui/layui_exts/dtree/dtree.css" rel="stylesheet" />  
  18.     <link href="../Scripts/layui/layui_exts/dtree/font/dtreefont.css" rel="stylesheet" />  
  19.     <script>  
  20.         document.write("<script type='text/javascript' src='../JS/ImageServiceDemo.js?rnd=" + Math.random() + "'><\/script>");  
  21.     </script>  
  22. </head>  
  23. <body>  
  24.     <div style="width:100%">  
  25.         <div style="float:left;margin-right:0px;margin-left20px;border-color:aquamarine">  
  26.             <ul id="imageTypesTree" class="dtree" data-id="0" style="width:300px;"></ul>  
  27.         </div>  
  28.         <div style="float:left;width:800px;">  
  29.             <div style="text-align:center" class="form-horizontal">  
  30.                 <div class="layui-progress layui-progress-big" lay-showPercent="yes">  
  31.                     <div class="layui-progress-bar layui-bg-green" lay-percent="0%" id="uploadProgress" style="display:none;"></div>  
  32.                 </div>  
  33.                 <div class="form-group">  
  34.                     <input type="file" multiple id="file" onchange="javascript:onc();" />  
  35.                 </div>  
  36.   
  37.                 <div class="form-group">  
  38.                     <label for="lastname" class="col-md-2 control-label">计划内码</label>  
  39.                     <div class="col-md-10">  
  40.                         <input type="text" class="form-control" id="jhid" placeholder="计划内码" value="f2617b63-264c-496d-a5de-14725c23941a">  
  41.                     </div>  
  42.                 </div>  
  43.   
  44.                 <div class="form-group">  
  45.                     <label for="lastname" class="col-md-2 control-label">移交记录内码</label>  
  46.                     <div class="col-md-10">  
  47.                         <input type="text" class="form-control" id="yjjlid" placeholder="计划内码" value="9e6b2a12-89a1-4b7c-81a9-3486aaad3474">  
  48.                     </div>  
  49.                 </div>  
  50.   
  51.                 <div class="form-group">  
  52.                     <label for="name" class="col-sm-2 control-label">请选择档案类别</label>  
  53.                     <div class="col-sm-10">  
  54.                         <select name="dassfl" id="dassfl" class="form-control">  
  55.                             <option value=""></option>  
  56.                             <option value="td">土地</option>  
  57.                             <option value="fwjzw">房屋建筑物</option>  
  58.                             <option value="swzc">实物资产</option>  
  59.                             <option value="fswzc">非实物资产</option>  
  60.                             <option value="cw">财务</option>  
  61.                             <option value="ry">人员</option>  
  62.                             <option value="da">档案</option>  
  63.                             <option value="wt">问题</option>  
  64.                         </select>  
  65.                     </div>  
  66.                 </div>  
  67.   
  68.                 <div class="form-group">  
  69.                     <button class="layui-btn layui-btn-radius layui-btn-normal" type="button" onclick="sendRequest();" style="width:150px;">上传大文件</button>  
  70.   
  71.                     <button id="btnUpload" class="layui-btn layui-btn-radius layui-btn-normal" type="button" style="width:150px;">上传</button>  
  72.   
  73.                     <button id="getFilesInfo" class="layui-btn layui-btn-radius layui-btn-normal" type="button" style="width:150px;" onclick="getFilesInfo();">获取附件</button>  
  74.                 </div>  
  75.                 <div style="text-align:center;margin-top:25px;">  
  76.                     <div id="filelist"></div>  
  77.                 </div>  
  78.   
  79.             </div>  
  80.         </div>  
  81.     </div>  
  82. </body>  
  83. </html>  

js脚本

  1. var uploadFiles = new Array();  
  2. var layer;  
  3. var dtree = null;  
  4. var imageTypesTree = null;  
  5. var selectTreeNodeId = '';  
  6.   
  7. var BYTES_PER_CHUNK = 1024 * 1024 * 2; // 每个文件切片大小定为2MB .  
  8. var slices;  
  9. var totalSlices;  
  10.   
  11. $(function () {  
  12.     $("#btnUpload").click(function () {  
  13.         checkFileExist(Upload);  
  14.     });  
  15.     layui.use('layer', function () {  
  16.         layer = layui.layer;  
  17.     });  
  18.     getImageType();  
  19.   
  20.     $('#dassfl').change(function () {  
  21.         getImageType();  
  22.     });  
  23. })  
  24.   
  25. function AddFiles(files) {  
  26.     var errstr = "";  
  27.     for (var i = 0; i < files.length; i++) {  
  28.         var filename = files[i].name;  
  29.         var isfind = false;  
  30.         for (var j = 0; j < uploadFiles.length; j++) {  
  31.             if (uploadFiles[j].name == filename) {  
  32.                 isfind = true;  
  33.                 break;  
  34.             }  
  35.         }  
  36.         var index1 = filename.lastIndexOf(".");  
  37.         var index2 = filename.length;  
  38.         var postf = filename.substring(index1 + 1, index2);//后缀名    
  39.         var myarray = new Array('JPG', 'jpg', 'jpeg', 'JPEG', 'gif', 'GIF', 'png', 'PNG');  
  40.         if (isfind == false) {  
  41.             uploadFiles.push(files[i]);  
  42.         }  
  43.         if (errstr != "") {  
  44.             layer.alert("文件格式错误:" + errstr);  
  45.         }  
  46.     }  
  47. }  
  48.   
  49. function onc() {  
  50.     var files = document.getElementById("file").files;  
  51.   
  52.     if (files.length < 0) {  
  53.         return;  
  54.     }  
  55.     AddFiles(files);  
  56. }  
  57.   
  58. function Upload() {  
  59.     var param = dtree.getNowParam(imageTypesTree);  
  60.     if (JSON.stringify(param) == "{}") {  
  61.         layer.alert('请选择档案类别');  
  62.         return;  
  63.     }  
  64.     var dalb = param.nodeId;  
  65.     var jhid = $('#jhid').val();  
  66.     var yjjlid = $('#yjjlid').val();  
  67.     var dassfl = $('#dassfl').val();  
  68.   
  69.     var files = document.getElementById("file").files;  
  70.     if (files.length <= 0) {  
  71.         alert('请先选择要上传的文件');  
  72.         return;  
  73.     }  
  74.     if (uploadFiles.length <= 0) {  
  75.         alert('上传成功');  
  76.         return;  
  77.     }  
  78.     var formData = new FormData();  
  79.     formData.append("file", uploadFiles[0]);  
  80.     formData.append('jhid', jhid);  
  81.     formData.append('dassfl', dassfl);  
  82.     formData.append('dalb', dalb);  
  83.     formData.append('yjjlid', yjjlid);  
  84.     $.ajax({  
  85.         url: "../Controller/ImageService.ashx?func=uploadimage",  
  86.         type: "POST",  
  87.         data: formData,  
  88.         processData: false,  
  89.         contentType: false,// 不设置内容类型  
  90.         success: function (data) {  
  91.             debugger  
  92.             var result = JSON.parse(data);  
  93.             if (result.IsSuccess != "1") {  
  94.                 alert(result.Msg);  
  95.             }  
  96.             uploadFiles.splice(0, 1);  
  97.             Upload();  
  98.         },  
  99.         error: function (XMLHttpRequest, textStatus, errorThrown) {  
  100.             alert(XMLHttpRequest.responseText);  
  101.         }  
  102.     });  
  103. }  
  104.   
  105. function checkFileExist(callBack) {  
  106.     var param = dtree.getNowParam(imageTypesTree);  
  107.     if (JSON.stringify(param) == "{}") {  
  108.         layer.alert('请选择档案类别');  
  109.         return;  
  110.     }  
  111.     var dalb = param.nodeId;  
  112.     var jhid = $('#jhid').val();  
  113.     var yjjlid = $('#yjjlid').val();  
  114.     var dassfl = $('#dassfl').val();  
  115.     var files = document.getElementById("file").files;  
  116.     if (files.length <= 0) {  
  117.         alert('请先选择要上传的文件');  
  118.         return;  
  119.     }  
  120.     var fileExistCheckArr = new Array();  
  121.     for (var i = 0; i < files.length; i++) {  
  122.         fileExistCheckArr.push(files[i].name);  
  123.     }  
  124.     $.ajax({  
  125.         url: "../Controller/ImageService.ashx?func=checkimageexist",  
  126.         type: "POST",  
  127.         async: false,  
  128.         data: { 'jhid': jhid, 'dassfl': dassfl, 'dalb': dalb, 'yjjlid': yjjlid, 'fileNames': JSON.stringify(fileExistCheckArr) },  
  129.         success: function (data) {  
  130.             debugger  
  131.             var result = JSON.parse(data);  
  132.             if (result.IsSuccess == "-1") {  
  133.                 layer.confirm(result.Msg, { icon: 3, title: '提示' }, function (index) {  
  134.                     if (index == 1) {  
  135.                         layer.closeAll();  
  136.                         callBack();  
  137.                     }  
  138.                 });  
  139.             } else {  
  140.                 callBack();  
  141.                 alert(result.Msg);  
  142.             }  
  143.         },  
  144.         error: function (XMLHttpRequest, textStatus, errorThrown) {  
  145.             alert(XMLHttpRequest.responseText);  
  146.         }  
  147.     });  
  148. }  
  149.   
  150. function getFilesInfo() {  
  151.     var param = dtree.getNowParam(imageTypesTree);  
  152.     if (JSON.stringify(param) == "{}") {  
  153.         layer.alert('请选择档案类别');  
  154.         return;  
  155.     }  
  156.     var dalb = param.nodeId;  
  157.     var jhid = 'f2617b63-264c-496d-a5de-14725c23941a';  
  158.     var dalb = '581ef7f3-4737-4258-8915-8c86f7121903';  
  159.     var yjjlid = '9e6b2a12-89a1-4b7c-81a9-3486aaad3474';  
  160.     var dassfl = $('#dassfl').val();  
  161.     if (dassfl == 'da') {  
  162.         jhid = 'f09fb1f1-f5f9-4fb9-aeed-2b03e2a50034';  
  163.         dalb = '43aba81f-e803-4db1-8a5c-b626853ebf28';  
  164.         yjjlid = '';  
  165.     }  
  166.     $.ajax({  
  167.         url: "../Controller/ImageService.ashx?func=getimage",  
  168.         type: "POST",  
  169.         async: false,  
  170.         data: { 'jhid': jhid, 'yjjlid': yjjlid, 'dassfl': dassfl },  
  171.         success: function (data) {  
  172.             debugger  
  173.             var result = JSON.parse(data);  
  174.             if (result.IsSuccess == "-1") {  
  175.   
  176.             } else {  
  177.                 var filelistArr = JSON.parse(result.Data);  
  178.                 $.each(filelistArr, function (index, value) {  
  179.                     $("#filelist").append("<a href='javascript:void(0)' id='" + value.FileID + "' FileID='" + value.FileID + "' BillID='" + value.BillID + "' FileType='" + value.FileType + "' onclick='downLoadImage(this)'>" + value.FileName + "</a><span onclick='deletefile(this)'>删除</span><br/>");  
  180.                 })  
  181.             }  
  182.         },  
  183.         error: function (XMLHttpRequest, textStatus, errorThrown) {  
  184.             alert(XMLHttpRequest.responseText);  
  185.         }  
  186.     });  
  187. }  
  188.   
  189. function downLoadImage(obj) {  
  190.     var fileid = $(obj)[0].id;  
  191.     var filename = $(obj).text();  
  192.     url = "../Controller/ImageService.ashx?func=downloadimage&fileid=" + fileid;  
  193.     var xhr = new XMLHttpRequest();  
  194.     xhr.open("POST", url, true);  
  195.     xhr.responseType = "blob";  
  196.     xhr.onload = function () {  
  197.         if (this.status == 200) {  
  198.             var blob = this.response;  
  199.             var reader = new FileReader();  
  200.             reader.readAsDataURL(blob);  
  201.             reader.onload = function (e) {  
  202.                 var a = document.createElement('a');  
  203.                 a.download = filename;  
  204.                 a.href = e.target.result;  
  205.                 document.body.appendChild(a);  
  206.                 a.click();  
  207.                 document.body.removeChild(a);  
  208.             }  
  209.         } else {  
  210.             layer.alert('获取文件失败');  
  211.         }  
  212.     };  
  213.     xhr.send();  
  214. }  
  215.   
  216.   
  217. function deletefile(obj) {  
  218.     var fileid = $(obj).prev("a").attr("FileID");  
  219.     var BillID = $(obj).prev("a").attr("BillID");  
  220.     var FileType = $(obj).prev("a").attr("FileType");  
  221.     var filename = $(obj).prev("a").text();  
  222.     var jhid = 'f2617b63-264c-496d-a5de-14725c23941a';  
  223.     var dalb = '581ef7f3-4737-4258-8915-8c86f7121903';  
  224.     var yjjlid = '9e6b2a12-89a1-4b7c-81a9-3486aaad3474';  
  225.     var dassfl = $('#dassfl').val();  
  226.     if (dassfl == 'da') {  
  227.         jhid = 'f09fb1f1-f5f9-4fb9-aeed-2b03e2a50034';  
  228.         dalb = '43aba81f-e803-4db1-8a5c-b626853ebf28';  
  229.         yjjlid = '';  
  230.     }  
  231.     $.ajax({  
  232.         url: "../Controller/ImageService.ashx?func=deleteimage",  
  233.         type: "POST",  
  234.         async: false,  
  235.         data: { 'fileid': fileid, 'filename': filename, 'jhid': jhid, 'yjjlid': yjjlid, 'dassfl': dassfl, 'dalb': dalb },  
  236.         success: function (data) {  
  237.             debugger  
  238.             var result = JSON.parse(data);  
  239.             if (result.IsSuccess == "-1") {  
  240.                 alert(result.Data);  
  241.             } else {  
  242.                 alert('删除成功');  
  243.             }  
  244.         },  
  245.         error: function (XMLHttpRequest, textStatus, errorThrown) {  
  246.             alert(XMLHttpRequest.responseText);  
  247.         }  
  248.     });  
  249. }  
  250.   
  251. function getImageType() {  
  252.   
  253.     var jhid = $('#jhid').val();  
  254.     var yjjlid = $('#yjjlid').val();  
  255.     var dassfl = $('#dassfl').val();  
  256.     var step = 'sjcj';  
  257.     debugger  
  258.     $.ajax({  
  259.         url: "../Controller/ZCJSMainPage.ashx?func=getimagetypetree",  
  260.         type: "POST",  
  261.         data: { step: step, dassfl: dassfl, jhid: jhid },  
  262.         success: function (data) {  
  263.             debugger  
  264.             var result = JSON.parse(data);  
  265.             if (result.success == "-1") {  
  266.                 layer.alert(result.msg);  
  267.             } else {  
  268.                 layui.config({  
  269.                     base: '../Scripts/layui/lay/modules/' //配置 layui 第三方扩展组件存放的基础目录  
  270.                 }).extend({  
  271.                     dtree: 'dtree'  
  272.                 }).use(['element', 'layer', 'dtree'], function () {  
  273.                     dtree = layui.dtree, layer = layui.layer, $ = layui.$;  
  274.                     // 初始化树                     
  275.                     imageTypesTree = dtree.render({  
  276.                         elem: "#imageTypesTree",  
  277.                         data: JSON.parse(result.data) // 使用data加载  
  278.                     });  
  279.                     // 绑定节点点击  
  280.                     dtree.on("node('imageTypesTree')"function (obj) {  
  281.                         selectTreeNodeId = obj.param.nodeId;  
  282.                         GetFilesInfoDATree(jhid, dassfl, '', step, obj.param.nodeId);  
  283.                     });  
  284.                 });  
  285.             }  
  286.         },  
  287.         error: function (XMLHttpRequest, textStatus, errorThrown) {  
  288.             layer.alert(XMLHttpRequest.responseText);  
  289.         }  
  290.     });  
  291. }  
  292.   
  293. //发送请求  
  294. function sendRequest() {  
  295.     var param = dtree.getNowParam(imageTypesTree);  
  296.     if (JSON.stringify(param) == "{}") {  
  297.         layer.alert('请选择档案类别');  
  298.         return;  
  299.     }  
  300.     var dalb = param.nodeId;  
  301.     var jhid = $('#jhid').val();  
  302.     var yjjlid = $('#yjjlid').val();  
  303.     var dassfl = $('#dassfl').val();  
  304.     var files = document.getElementById("file").files;  
  305.     while (uploadFiles.length > 0) {  
  306.         var blob = uploadFiles[0];  
  307.         var start = 0;  
  308.         var end;  
  309.         var index = 0;  
  310.         var guid = newGuid();  
  311.         console.log(guid);  
  312.         // 计算文件切片总数  
  313.         slices = Math.ceil(blob.size / BYTES_PER_CHUNK);  
  314.         totalSlices = slices;  
  315.         while (start < blob.size) {  
  316.             end = start + BYTES_PER_CHUNK;  
  317.             if (end > blob.size) {  
  318.                 end = blob.size;  
  319.             }  
  320.             if (uploadFile(blob, index, start, end, guid, jhid, yjjlid, dassfl, dalb) < 0) {  
  321.                 break;  
  322.             }  
  323.             start = end;  
  324.             index++;  
  325.             if (index >= totalSlices) {  
  326.                 $("#uploadProgress").css('display', 'none');  
  327.             }  
  328.         }  
  329.         uploadFiles.splice(0, 1);  
  330.     }  
  331. }  
  332.   
  333. //上传文件  
  334. function uploadFile(blob, index, start, end, guid, jhid, yjjlid, dassfl, dalb) {  
  335.     var formData;  
  336.     var chunk;  
  337.     var sliceIndex = blob.name + index;  
  338.     chunk = blob.slice(start, end);//切割文件  
  339.     formData = new FormData();  
  340.     formData.append("FileName", chunk, sliceIndex);  
  341.     formData.append("filename", blob.name);  
  342.     formData.append("chunk", index);  
  343.     formData.append("sliceIndex", sliceIndex);  
  344.     formData.append("chunks", totalSlices);  
  345.     formData.append('jhid', jhid);  
  346.     formData.append('dassfl', dassfl);  
  347.     formData.append('dalb', dalb);  
  348.     formData.append('yjjlid', yjjlid);  
  349.     formData.append('guid', guid);  
  350.     $.ajax({  
  351.         url: '../Controller/ImageService.ashx?func=uploadimage',  
  352.         type: "POST",  
  353.         data: formData,  
  354.         processData: false,  
  355.         contentType: false,// 不设置内容类型  
  356.         success: function (data) {  
  357.             var result = JSON.parse(data);  
  358.             var currentChunk = parseInt(data.Msg);  
  359.             if (result.IsSuccess == "0") {  
  360.                 var percent = parseInt((currentChunk / totalSlices) * 100);  
  361.                 $("#uploadProgress").css('display', 'block').attr('lay-percent', percent.toFixed() + '%');  
  362.                 return 0;  
  363.             } else if (result.IsSuccess == "1") {  
  364.                 layer.alert('上传完成');  
  365.                 return 1;  
  366.             } else {  
  367.                 layer.alert('上传失败,原因为:' + result.Msg);  
  368.                 return -1;  
  369.             }  
  370.         },  
  371.         error: function (XMLHttpRequest, textStatus, errorThrown) {  
  372.             alert(XMLHttpRequest.responseText);  
  373.         }  
  374.     });  
  375. }  
  376.   
  377. function newGuid() {  
  378.     return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {  
  379.         var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);  
  380.         return v.toString(16);  
  381.     });  
  382. }  

一般处理程序

  1. #region 上传影像文件  
  2.         /// <summary>  
  3.         /// 上传影像  
  4.         /// </summary>  
  5.         /// <param name="context"></param>  
  6.         public void UploadImage(HttpContext context)  
  7.         {  
  8.             string jhid = string.Empty;//计划ID  
  9.             string dassfl = string.Empty;//档案所属分类  
  10.             string yjjlid = string.Empty;//移交记录ID  
  11.             string dalb = string.Empty;//档案类别  
  12.             string rwjd = string.Empty;//任务阶段  
  13.             HttpFileCollection files = context.Request.Files; ;//要检查的文件列表  
  14.             string result = string.Empty;  
  15.             if (!context.Request.Params.AllKeys.Contains("jhid"))  
  16.             {  
  17.                 result += "计划ID不能为空;";  
  18.             }  
  19.             if (!context.Request.Params.AllKeys.Contains("dassfl"))  
  20.             {  
  21.                 result += "所属分类不能为空;";  
  22.             }  
  23.             if (!context.Request.Params.AllKeys.Contains("dalb"))  
  24.             {  
  25.                 result += "附件类别不能为空;";  
  26.             }  
  27.             jhid = context.Request.Params["jhid"];  
  28.             dassfl = ConvertDassfl2Lower(context.Request.Params["dassfl"]);  
  29.             dalb = context.Request.Params["dalb"];  
  30.             if (context.Request.Params.AllKeys.Contains("yjjlid"))  
  31.             {  
  32.                 yjjlid = context.Request.Params["yjjlid"];  
  33.             }  
  34.             if (context.Request.Params.AllKeys.Contains("rwjd"))  
  35.             {  
  36.                 rwjd = context.Request.Params["rwjd"];  
  37.             }  
  38.             if (context.Request.Form.AllKeys.Contains("chunk"))  
  39.             {  
  40.                 //取得chunk和chunks  
  41.                 int chunk = Convert.ToInt32(context.Request.Form["chunk"]);//当前分片在上传分片中的顺序(从0开始)  
  42.                 int chunks = Convert.ToInt32(context.Request.Form["chunks"]);//总分片数  
  43.                 string fileName = context.Request.Form["filename"];//文件实际名称  
  44.                 string guid = context.Request.Form["guid"]; ;  
  45.                 //根据GUID创建用该GUID命名的临时文件夹  
  46.                 string folder = fileSavePath + "\\" + guid + "\\"; 
  47.                 string path = folder + chunk; 
  48.                 //建立临时传输文件夹 
  49.                 if (!Directory.Exists(Path.GetDirectoryName(folder))) 
  50.                 { 
  51.                     Directory.CreateDirectory(folder); 
  52.                 } 
  53.                 FileStream addFile = new FileStream(path, FileMode.Append, FileAccess.Write); 
  54.                 BinaryWriter AddWriter = new BinaryWriter(addFile); 
  55.                 //获得上传的分片数据流 
  56.                 HttpPostedFile file = context.Request.Files[0]; 
  57.                 Stream stream = file.InputStream; 
  58.                 BinaryReader TempReader = new BinaryReader(stream); 
  59.                 //将上传的分片追加到临时文件末尾 
  60.                 AddWriter.Write(TempReader.ReadBytes((int)stream.Length)); 
  61.                 //关闭BinaryReader文件阅读器 
  62.                 TempReader.Close(); 
  63.                 stream.Close(); 
  64.                 AddWriter.Close(); 
  65.                 addFile.Close(); 
  66.                 TempReader.Dispose(); 
  67.                 stream.Dispose(); 
  68.                 AddWriter.Dispose(); 
  69.                 addFile.Dispose(); 
  70.                 //合并文件 
  71.                 ProcessRequestFiles(guid, fileName, chunks, jhid, dassfl, yjjlid, dalb, rwjd); 
  72.             } 
  73.             else 
  74.             { 
  75.  
  76.                 if (files.Count <= 0) 
  77.                 { 
  78.                     result += "文件信息不能为空;"; 
  79.                 } 
  80.                 if (!string.IsNullOrEmpty(result)) 
  81.                 { 
  82.                     ResponseInfo responseInfo = new ResponseInfo 
  83.                     { 
  84.                         IsSuccess = "-1", 
  85.                         Msg = result.TrimEnd(';'), 
  86.                         Data = ""  
  87.                     };  
  88.                     context.Response.Write(JsonConvert.SerializeObject(responseInfo));  
  89.                 }  
  90.                 else//执行判断  
  91.                 {  
  92.                     ResponseInfo responseInfo = new ResponseInfo();  
  93.                     string msg = string.Empty;  
  94.                     responseInfo.IsSuccess = ImageServiceCore.CreateInstance().UploadImage(jhid, dassfl, yjjlid, dalb, files, out msg);  
  95.                     responseInfo.Msg = msg;  
  96.                     context.Response.Write(JsonConvert.SerializeObject(responseInfo));  
  97.                 }  
  98.             }  
  99.         }  
  100.         #endregion  
  1. private void ProcessRequestFiles(string guid, string fileName, int chunks, string jhid, string dassfl, string yjjlid, string dalb, string rwjd)  
  2.         {  
  3.             HttpContext context = System.Web.HttpContext.Current;  
  4.             context.Response.ContentType = "text/plain";  
  5.             string sourcePath = fileSavePath + "\\" + guid + "\\";//源数据文件夹 
  6.             string targetPath = fileSavePath + "\\" + guid + "\\" + fileName;//合并后的文件 
  7.             DirectoryInfo dicInfo = new DirectoryInfo(sourcePath); 
  8.             ResponseInfo responseInfo = new ResponseInfo(); 
  9.             try 
  10.             { 
  11.                 if (Directory.Exists(sourcePath)) 
  12.                 { 
  13.                     FileInfo[] files = dicInfo.GetFiles(); 
  14.                     if (files.Length != chunks) 
  15.                     { 
  16.                         responseInfo = new ResponseInfo 
  17.                         { 
  18.                             IsSuccess = "0", 
  19.                             Msg = "", 
  20.                             Data = "" 
  21.                         }; 
  22.                         context.Response.Write(JsonConvert.SerializeObject(responseInfo)); 
  23.                         return; 
  24.                     } 
  25.                     foreach (FileInfo file in files.OrderBy(f => int.Parse(f.Name))) 
  26.                     { 
  27.                         FileStream addFile = new FileStream(targetPath, FileMode.Append); 
  28.                         BinaryWriter AddWriter = new BinaryWriter(addFile); 
  29.                         //获得上传的分片数据流 
  30.                         Stream stream = file.Open(FileMode.Open); 
  31.                         BinaryReader TempReader = new BinaryReader(stream); 
  32.                         //将上传的分片追加到临时文件末尾 
  33.                         AddWriter.Write(TempReader.ReadBytes((int)stream.Length)); 
  34.                         //关闭BinaryReader文件阅读器 
  35.                         TempReader.Close(); 
  36.                         stream.Close(); 
  37.                         AddWriter.Close(); 
  38.                         addFile.Close(); 
  39.                         TempReader.Dispose(); 
  40.                         stream.Dispose(); 
  41.                         AddWriter.Dispose(); 
  42.                         addFile.Dispose(); 
  43.                     } 
  44.                     using (FileStream fileStream = new FileStream(targetPath, FileMode.Open)) 
  45.                     { 
  46.                         string msg = string.Empty; 
  47.                         responseInfo.IsSuccess = ImageServiceCore.CreateInstance().UploadImage(jhid, dassfl, yjjlid, dalb, fileStream, fileName, rwjd, out msg); 
  48.                         responseInfo.Msg = msg; 
  49.                         responseInfo.Data = chunks.ToString(); 
  50.                     } 
  51.                     //删除文件夹 
  52.                     string delPath = fileSavePath + "\\" + guid; 
  53.                     if (Directory.Exists(delPath)) 
  54.                     { 
  55.                         Directory.Delete(delPath, true); 
  56.                     } 
  57.                     context.Response.Write(JsonConvert.SerializeObject(responseInfo)); 
  58.                 } 
  59.                 else 
  60.                 { 
  61.                     responseInfo = new ResponseInfo 
  62.                     { 
  63.                         IsSuccess = "-1", 
  64.                         Msg = "获取存储目录失败", 
  65.                         Data = "" 
  66.                     }; 
  67.                     context.Response.Write(JsonConvert.SerializeObject(responseInfo)); 
  68.                 } 
  69.             } 
  70.             catch (Exception ex) 
  71.             { 
  72.                 responseInfo = new ResponseInfo 
  73.                 { 
  74.                     IsSuccess = "-1", 
  75.                     Msg = ex.Message, 
  76.                     Data = ""  
  77.                 };  
  78.                 context.Response.Write(JsonConvert.SerializeObject(responseInfo));  
  79.             }  
  80.         }  

历史上的今天:

本文地址:https://www.lisen.me/dotnet-and-ajax-for-block-upload.html
版权声明:本文为原创文章,版权归 木子网 所有,欢迎分享本文,转载请保留出处!
NEXT:已经是最新一篇了

发表评论


表情