TotalFileParts.ToString());FilePartName = Path.Combine(Temp

时间:2022-05-04 09:09:22

盘问很多资料没有遇到合适的,对付MultipartFormDataStreamProvider 也并是很适合,总会呈现问题。于是放弃,使用了传统的InputStream 分段措置惩罚惩罚完之后做merge措置惩罚惩罚。

前台分段法则 定名要规范,通报分段总文件数便于判定分段上传完成做merge措置惩罚惩罚。merge需要按照分段挨次并在merge告成后删除分段文件。

var FilePartName = file.name + ".part_" + PartCount + "." + TotalParts;

前台JS代码:

<script> $(document).ready(function () { $(‘#btnUpload‘).click(function () { var files = $(‘#uploadfile‘)[0].files; for (var i = 0; i < files.length; i++) { UploadFile(files[i]); } } ); }); function UploadFileChunk(Chunk, FileName) { var fd = new FormData(); fd.append(‘file‘, Chunk, FileName); fd.append(‘UserName‘, ‘[email protected]‘); fd.append(‘BusinessLine‘, ‘1‘); fd.append(‘ServiceItemType‘, ‘109‘); fd.append(‘Comment‘, ‘This is order comment for GA order‘); fd.append(‘UserId‘, ‘43F0FEDF-E9AF-4289-B71B-54807BCB8CD9‘); $.ajax({ type: "POST", url: ‘:50821/api/customer/GA/SaveSangerCameraOrder‘, contentType: false, processData: false, data: fd, success: function (data) { alert(data); }, error: function (data) { alert(data.status + " : " + data.statusText + " : " + data.responseText); } }); } function UploadFile(TargetFile) { // create array to store the buffer chunks var FileChunk = []; // the file object itself that we will work with var file = TargetFile; // set up other initial vars var MaxFileSizeMB = 5; var BufferChunkSize = MaxFileSizeMB * (1024 * 1024); var ReadBuffer_Size = 1024; var FileStreamPos = 0; // set the initial chunk length var EndPos = BufferChunkSize; var Size = file.size; // add to the FileChunk array until we get to the end of the file while (FileStreamPos < Size) { // "slice" the file from the starting position/offset, to the required length FileChunk.push(file.slice(FileStreamPos, EndPos)); FileStreamPos = EndPos; // jump by the amount read EndPos = FileStreamPos + BufferChunkSize; // set next chunk length } // get total number of "files" we will be sending var TotalParts = FileChunk.length; var PartCount = 0; // loop through, pulling the first item from the array each time and sending it while (chunk = FileChunk.shift()) { PartCount++; // file name convention var FilePartName = file.name + ".part_" + PartCount + "." + TotalParts; // send the file UploadFileChunk(chunk, FilePartName); } } </script>

MaxFileSizeMB参数设置分段巨细 ,,测试例子为5M chunk = FileChunk.shift() 在分段上传告成之后删除已上传分段

1

 

HTML代码:

 

<h2>Test Multiple Chunk Upload</h2> <p> <input type="file" multiple="multiple" /> <br /> <a href="#">Upload file</a> </p>

后台webapi controller代码:

/// <summary> /// Upload sanger camera order /// </summary> /// <param>user id and user email are required</param> /// <returns></returns> [HttpPost] [Route("api/customer/GA/SaveSangerCameraOrder")] [MimeMultipart] public HttpResponseMessage SaveSangerCameraOrder() { var files = HttpContext.Current.Request.Files; if (files.Count <= 0) { return new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(ConstantStringHelper.API_FAILED) }; }         //receice request form parameters var userName = HttpContext.Current.Request.Form["UserName"]; var businessLine = HttpContext.Current.Request.Form["BusinessLine"]; var serviceItemType = HttpContext.Current.Request.Form["ServiceItemType"]; var comment = HttpContext.Current.Request.Form["Comment"]; var userId = HttpContext.Current.Request.Form["UserId"]; if (string.IsNullOrEmpty(userName)) userName = "UnknownUser"; string dateTimeTicket = string.Format("{0:yyyy-MM-dd}", System.DateTime.Now); var storagePath = ConfigurationManager.AppSettings["SangerOrderStorageLocation"].ToString(); var fileSavePath = storagePath + @"http://www.mamicode.com/" + userName + "http://www.mamicode.com/" + dateTimeTicket + "http://www.mamicode.com/"; foreach (string file in files) { var FileDataContent = HttpContext.Current.Request.Files[file]; if (FileDataContent != null && FileDataContent.ContentLength > 0) { // take the input stream, and save it to a temp folder using // the original file.part name posted var stream = FileDataContent.InputStream; var fileName = Path.GetFileName(FileDataContent.FileName); var UploadPath = HttpContext.Current.Request.MapPath(fileSavePath); Directory.CreateDirectory(UploadPath); string path = Path.Combine(UploadPath, fileName); if (System.IO.File.Exists(path)) System.IO.File.Delete(path); using (var fileStream = System.IO.File.Create(path)) { stream.CopyTo(fileStream); } // Once the file part is saved, see if we have enough to merge it Utils UT = new Utils(); var isMergedSuccess = UT.MergeFile(path); if (isMergedSuccess) { //generate txt document for customer comment string timeTicket = string.Format("{0:yyyyMMddHHmmss}", System.DateTime.Now); FileStream fs = new FileStream(UploadPath + timeTicket + "OrderComment.txt", FileMode.Create); //get byte byte[] data = System.Text.Encoding.Default.GetBytes(comment); //write fs.Write(data, 0, data.Length); //clear and clost stream fs.Flush(); fs.Close(); } } } return new HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(ConstantStringHelper.API_SUCCESS) }; }

工具类代码:

记得*stream