asp.net mvc+webuploader大文件分片上传

首先是前端:

 1 var GUID = WebUploader.Base.guid();//一个GUID
 2     uploadereditsVideo = WebUploader.create({
 3         // swf文件路径
 4         swf: '../../Scripts/plugins/webuploader/Uploader.swf',
 5         // 文件接收服务端。
 6         server: '/AjaxUpload/ChunkUpload',
 7         pick: {
 8             id: '#picker',
 9             label: '上传',
10             innerHTML: '上传',
11             multiple: false
12         },
13         fileNumLimit: 1,
14         fileSingleSizeLimit: 1024 * 1024 *100,
15         chunked: true,//开始分片上传
16         chunkSize: 1024 * 1024 * 2,//每一片的大小
17         formData: {
18             guid: GUID //自定义参数
19         }
20     });
21 
22     uploadereditsVideo.on('fileQueued', function (file) {
23         uploadereditsVideo.upload();
24     });
25     // 文件上传成功
26     uploadereditsVideo.on('uploadSuccess', function (file, response) {
27         //合并文件
28         $.post('/AjaxUpload/Merge', { guid: GUID, fileName: file.name }, function (data) {
29             if (data.r == 1) {
30                 alert("上传完成");
31             }
32             else {
33                 alert(data.err);
34             }
35         });
36     });

后端接收方法Upload

 1 public ActionResult Upload()
 2         {
 3             //如果进行了分片
 4             if (Request.Form.AllKeys.Any(m => m == "chunk"))
 5             {
 6                 //取得chunk和chunks
 7                 int chunk = Convert.ToInt32(Request.Form["chunk"]);//当前分片在上传分片中的顺序(从0开始)
 8                 int chunks = Convert.ToInt32(Request.Form["chunks"]);//总分片数
 9                 //根据GUID创建用该GUID命名的临时文件夹
10                 string folder = Server.MapPath("~/upload/" + Request["guid"] + "/");
11                 string path = folder + chunk;
12 
13                 //建立临时传输文件夹
14                 if (!Directory.Exists(Path.GetDirectoryName(folder)))
15                 {
16                     Directory.CreateDirectory(folder);
17                 }
18 
19                 FileStream addFile = new FileStream(path, FileMode.Append, FileAccess.Write);
20                 BinaryWriter AddWriter = new BinaryWriter(addFile);
21                 //获得上传的分片数据流
22                 var file = Request.Files[0];
23                 Stream stream = file.InputStream;
24 
25                 BinaryReader TempReader = new BinaryReader(stream);
26                 //将上传的分片追加到临时文件末尾
27                 AddWriter.Write(TempReader.ReadBytes((int)stream.Length));
28                 //关闭BinaryReader文件阅读器
29                 TempReader.Close();
30                 stream.Close();
31                 AddWriter.Close();
32                 addFile.Close();
33 
34                 TempReader.Dispose();
35                 stream.Dispose();
36                 AddWriter.Dispose();
37                 addFile.Dispose();
38                 return Json(new { chunked = true, hasError = false, f_ext = Path.GetExtension(file.FileName) });
39             }
40             else//没有分片直接保存
41             {
42                 Request.Files[0].SaveAs(Server.MapPath("~/upload/" + DateTime.Now.ToFileTime() + Path.GetExtension(Request.Files[0].FileName)));
43                 return Json(new { chunked = true, hasError = false });
44             }
45         }

合并方法Merge

public ActionResult Merge()
        {
            try
            {
                var guid = Request["guid"];//GUID
                var uploadDir = Server.MapPath("~/upload");//Upload 文件夹
                var dir = Path.Combine(uploadDir, guid);//临时文件夹
                var ext = Path.GetExtension(Request["fileName"]);
                var files = Directory.GetFiles(dir);//获得下面的所有文件
                var name = Guid.NewGuid().ToString("N") + ext;
                var finalPath = Path.Combine(uploadDir, name);//最终的文件名
                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();
                Directory.Delete(dir);//删除文件夹
                return Json(new { r = 1, path = "/upload/" + name });
            }
            catch (Exception ex)
            {
                return Json(new { r = 0, err = ex.Message });
            }
        }

以上就是分片上传的方法

原文地址:https://www.cnblogs.com/war-hzl/p/7560083.html