asp.net core分块上传文件

  写完asp.net多文件上传(http://www.cnblogs.com/bestckk/p/5987383.html)后,感觉这种上传还是有很多缺陷,于是。。。(省略一万字,不废话)。这里我没用传统的asp.net,而选择了开源的asp.net core,原因很简单,.net core是.net新的开始,更是.net和.net开发者的未来,希望.net发展越来越好(大家的工资越来越高(●ˇ∀ˇ●))。

  1.前端的实现:

    1).html: 

 1 <html>
 2 <head>
 3     <meta name="viewport" content="width=device-width" />
 4     <title>Index</title>
 5     <link href="/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
 6     <script src="/lib/jquery/dist/jquery.js"></script>
 7     <script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
 8     <script src="/js/UploadJs.js"></script>
 9 </head>
10 <body>
11     <div class="row" style="margin-top:20%">
12         <div class="col-lg-4"></div>
13         <div class="col-lg-4">
14             <input type="text" value="请选择文件" size="20" name="upfile" id="upfile" style="border:1px dotted #ccc">
15             <input type="button" value="浏览" onclick="path.click()" style="border:1px solid #ccc;background:#fff">
16             <input type="file" id="path" style="display:none" multiple="multiple" onchange="upfile.value=this.value">
17             <br />
18             <span id="output">0%</span>
19             <button type="button" id="file" onclick="UploadStart()" style="border:1px solid #ccc;background:#fff">开始上传</button>
20         </div>
21         <div class="col-lg-4"></div>
22     </div>
23 </body>
24 </html>

    2).javascript:

 1 var UploadPath = "";
 2 //开始上传
 3 function UploadStart() {
 4     var file = $("#path")[0].files[0];
 5     AjaxFile(file, 0);
 6 }
 7 function AjaxFile(file, i) {
 8     var name = file.name, //文件名
 9     size = file.size, //总大小shardSize = 2 * 1024 * 1024, 
10     shardSize = 2 * 1024 * 1024,//以2MB为一个分片
11     shardCount = Math.ceil(size / shardSize); //总片数
12     if (i >= shardCount) {
13         return;
14     }
15     //计算每一片的起始与结束位置
16     var start = i * shardSize,
17     end = Math.min(size, start + shardSize);
18     //构造一个表单,FormData是HTML5新增的
19     var form = new FormData();
20     form.append("data", file.slice(start, end)); //slice方法用于切出文件的一部分
21     form.append("lastModified", file.lastModified);
22     form.append("fileName", name);
23     form.append("total", shardCount); //总片数
24     form.append("index", i + 1); //当前是第几片
25     UploadPath = file.lastModified
26     //Ajax提交文件
27     $.ajax({
28         url: "/Upload/UploadFile",
29         type: "POST",
30         data: form,
31         async: true, //异步
32         processData: false, //很重要,告诉jquery不要对form进行处理
33         contentType: false, //很重要,指定为false才能形成正确的Content-Type
34         success: function (result) {
35             if (result != null) {
36                 i = result.number++;
37                 var num = Math.ceil(i * 100 / shardCount);
38                 $("#output").text(num + '%');
39                 AjaxFile(file, i);
40                 if (result.mergeOk) {
41                     var filepath = $("#path");
42                     filepath.after(filepath.clone().val(""));
43                     filepath.remove();//清空input file
44                     $('#upfile').val('请选择文件');
45                     alert("success!!!");
46                 }
47             }
48         }
49     });
50 }

    这里的主要思路是利用html5 File api的slice方法把文件分块,然后new一个FormData()对象用于储存文件数据,之后就是递归调用AjaxFile方法直至上传完毕。

  2.后台C#:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Mvc;
 6 using System.IO;
 7 
 8 // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
 9 
10 namespace DotNet.Upload.Controllers
11 {
12     public class UploadController : Controller
13     {
14         // GET: /<controller>/
15         public IActionResult Index()
16         {
17             return View();
18         }
19 
20         [HttpPost]
21         public async Task<ActionResult> UploadFile()
22         {
23             var data = Request.Form.Files["data"];
24             string lastModified = Request.Form["lastModified"].ToString();
25             var total = Request.Form["total"];
26             var fileName = Request.Form["fileName"];
27             var index = Request.Form["index"];
28 
29             string temporary = Path.Combine(@"E:\浏览器", lastModified);//临时保存分块的目录
30             try
31             {
32                 if (!Directory.Exists(temporary))
33                     Directory.CreateDirectory(temporary);
34                 string filePath = Path.Combine(temporary, index.ToString());
35                 if (!Convert.IsDBNull(data))
36                 {
37                     await Task.Run(() => {
38                         FileStream fs = new FileStream(filePath, FileMode.Create);
39                         data.CopyTo(fs);
40                     });
41                 }
42                 bool mergeOk = false;
43                 if (total == index)
44                 {
45                     mergeOk = await FileMerge(lastModified, fileName);
46                 }
47 
48                 Dictionary<string, object> result = new Dictionary<string, object>();
49                 result.Add("number", index);
50                 result.Add("mergeOk", mergeOk);
51                 return Json(result);
52 
53             }
54             catch (Exception ex)
55             {
56                 Directory.Delete(temporary);//删除文件夹
57                 throw ex;
58             }
59         }
60 
61         public async Task<bool> FileMerge(string lastModified,string fileName)
62         {
63             bool ok = false;
64             try
65             {
66                 var temporary = Path.Combine(@"E:\浏览器", lastModified);//临时文件夹
67                 fileName = Request.Form["fileName"];//文件名
68                 string fileExt = Path.GetExtension(fileName);//获取文件后缀
69                 var files = Directory.GetFiles(temporary);//获得下面的所有文件
70                 var finalPath = Path.Combine(@"E:\浏览器", DateTime.Now.ToString("yyMMddHHmmss") + fileExt);//最终的文件名(demo中保存的是它上传时候的文件名,实际操作肯定不能这样)
71                 var fs = new FileStream(finalPath, FileMode.Create);
72                 foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序,保证从0-N Write
73                 {
74                     var bytes = System.IO.File.ReadAllBytes(part);
75                     await fs.WriteAsync(bytes, 0, bytes.Length);
76                     bytes = null;
77                     System.IO.File.Delete(part);//删除分块
78                 }
79                 fs.Close();
80                 Directory.Delete(temporary);//删除文件夹
81                 ok = true;
82             }
83             catch (Exception ex)
84             {
85                 throw ex;
86             }
87             return ok;
88         }
89 
90     }
91 }

  这里的思路就是先保存每一个分块的文件到一个临时文件夹,最后再通过FileStream合并这些临时文件(合并时必需要按顺序)。后台的方法都进行了异步化(async await真的非常好用),虽然不知道对效率有没有提升,但是就是觉得这样很酷。

  源码:http://pan.baidu.com/s/1bDdsEa

 

posted @ 2016-11-25 22:18  天空的影子  阅读(5121)  评论(6编辑  收藏  举报