123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- 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<double> 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;
- }
- /// <summary>
- /// 将内容写入流
- /// </summary>
- /// <param name="stream"></param>
- /// <param name="context"></param>
- /// <returns></returns>
- 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);
- }
- /// <summary>
- /// 比较文件大小
- /// </summary>
- /// <returns></returns>
- 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;
- }
- }
- }
|