using System; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using WingInterfaceLibrary.DTO.Report; using WingServerCommon.Log; namespace WingAIDiagnosisService.Manage { public class UploadContent : HttpContent { private const int ChunkSize = 2097152;//2M; private readonly Stream _uploadStream; private readonly long _fileSize; public event EventHandler ProgressChanged; public UploadContent(string filePath) { if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath)) { throw new Exception("UploadFile not find"); } var fileName = Path.GetFileName(filePath); _uploadStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); var mimeType = FileHelper.GetMimeType(fileName.Substring(fileName.LastIndexOf("."))); Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType); Headers.ContentLength = _uploadStream.Length; _fileSize = _uploadStream.Length; } public UploadContent(byte[] fileData, MediaTypeHeaderValue mediaTypeHeaderValue) { if (fileData == null || fileData.Length == 0) { throw new Exception("FileData is empty"); } _uploadStream = new MemoryStream(fileData); Headers.ContentType = mediaTypeHeaderValue; Headers.ContentLength = _uploadStream.Length; _fileSize = _uploadStream.Length; } /// /// 将内容写入流 /// /// /// /// protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { for (long i = 0; i < _uploadStream.Length; i += ChunkSize) { var dataToWrite = new byte[Math.Min(ChunkSize, _uploadStream.Length - i)]; await _uploadStream.ReadAsync(dataToWrite, 0, dataToWrite.Length); await stream.WriteAsync(dataToWrite, 0, dataToWrite.Length); OnProgressChanged((double)(i * 100 / _uploadStream.Length)); } OnProgressChanged(100); } /// /// 比较文件大小 /// /// public bool CompareFileSizes(long webFileSize) { return _fileSize == webFileSize; } protected override bool TryComputeLength(out long length) { length = _uploadStream.Length; return true; } private void OnProgressChanged(double e) { ProgressChanged?.Invoke(this, e); } public new void Dispose() { base.Dispose(); _uploadStream.Close(); ProgressChanged = null; } } }