/// <summary> /// 开始上传 /// </summary> /// <param name="upload"></param> public async void UploadStart(Upload upload) { UploadStatus = UploadStatus.Uploading; if (upload != null && upload.FileType != (int)FileType.UNKNOWN) { using (FileStream fileStream = new FileStream(upload.FilePath, FileMode.Open, FileAccess.Read)) { var buffer = new byte[CHUNKSIZE]; int chunkNumber = upload.ChunkNumber; int totalSize = upload.FileSize; int totalChunks = (int)Math.Ceiling((double)totalSize / CHUNKSIZE); int bytesRead = 0; int offset = chunkNumber * CHUNKSIZE; int uploadedLength = offset; fileStream.Seek((long)offset, SeekOrigin.Begin); while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { //如果暂停了 if (UploadStatus == UploadStatus.Pause) { break; } //开始时间 var watch = new Stopwatch(); watch.Start(); //byte转换 var finalBuffer = new byte[bytesRead]; Buffer.BlockCopy(buffer, 0, finalBuffer, 0, bytesRead); //上传一个分片 var response = await HttpManager.Instance.BreakPointUploadAsync <BreakPointUploadResponse>( new UploadAlbumFileRequest(upload.TargetId, upload.AlbumId, (AlbumType)upload.AlbumType, upload.FileName, (FileType)upload.FileType, upload.Identifier, totalSize, totalChunks, chunkNumber, CHUNKSIZE, bytesRead), finalBuffer ); Logger.Log(response.message); //当前分片上传失败(只要不是完成和分片成功都视为失败) if (!response.Ok && response.code != 201) { OnUploadFailure?.Invoke(); break; } //上传完成 if (response.Ok) { OnUploadCompleted?.Invoke(); UploadManager.DeleteUploader(upload); break; } var progress = Convert.ToDouble((uploadedLength / (Double)totalSize) * 100); //当前分片上传成功 upload.Progress = progress; upload.ChunkNumber = chunkNumber; var a = UploadManager.UpdateUploader(upload); chunkNumber++;//文件块序号+1 //结束时间 watch.Stop(); uploadedLength += bytesRead; //速度计算byte/s var speed = CHUNKSIZE * 1000L / watch.ElapsedMilliseconds; //计算剩余时间 var time = (totalSize - uploadedLength) / speed; //上传进度通知 OnUploadProgressChanged?.Invoke(progress, (int)time, speed / 1024); } } } }