1. 客户每次上传前先获取一下当前文件已经被服务器接受了多少
2. 上传时设定偏移量
服务端代码如下:
/// <summary> /// 断点续传 服务端保存文件代码 /// </summary> /// <returns></returns> [HttpPost] public bool UploadEcgData() { bool result = false; FileStream fStream = null; BinaryReader bReader = null; try { long offset = 0; //客户端定义,从X开始往后写,该值由服务端GetFileLength方法提供 IEnumerable<string> hasOffsetList = new List<string>(); bool hasOffset = Request.Headers.TryGetValues("Offset", out hasOffsetList); if (hasOffset && hasOffsetList.Any()) { long.TryParse(hasOffsetList.First(), out offset); } HttpPostedFile file = HttpContext.Current.Request.Files[0]; //设置文件存放路径 string dir = HttpContext.Current.Server.MapPath(@"~\UploadFiles"); int upLoadLength = Convert.ToInt32(file.InputStream.Length); fStream = new FileStream(dir + "\\" + file.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); //偏移指针 fStream.Seek(offset, SeekOrigin.Begin); //从客户端的请求中获取文件流 bReader = new BinaryReader(file.InputStream); byte[] data = new byte[upLoadLength]; bReader.Read(data, 0, upLoadLength); //将上传文件流读到byte[]中 fStream.Write(data, 0, upLoadLength);//将byte[]写到文件中, result = true; } catch (Exception ex) { logger.Error(ex, ex.Message); result = false; } finally { if (fStream != null) { //释放流 fStream.Close(); } if (bReader != null) { bReader.Close(); } } return result; }
上传前,源和目标文件对比
用 Postman 测试
上传后的源和目标文件对比