當前環境 .net framework 4.8
HttpClient 使用GzipStream壓縮文件並上傳到WebApi
if (this.Config.URL.EndsWith("/"))
postURL = this.Config.URL + "Upload/UploadFile?token=" + this.Config.Token;
else
postURL = this.Config.URL + "/Upload/UploadFile?token=" + this.Config.Token;
var currentFiles = Directory.GetFiles(directoryPath);
foreach (var fileFullName in currentFiles)
{
if (CheckCancel())
{
ServiceLog.Log("to Service EndTime, stop services....");
return;
}
string fileName = string.Empty;
try
{
string contentType = MimeMapping.GetMimeMapping(fileFullName);
if (!this.Config.FileTypes.Any(cType => cType == contentType))
continue;
FileInfo fileInfo = new FileInfo(fileFullName);
fileName = fileInfo.Name;
byte[] fileBytes = File.ReadAllBytes(fileFullName);
byte[] compressedFileByes = null;
//compress
using (var memoryStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress))
{
gzipStream.Write(fileBytes, 0, fileBytes.Length);
gzipStream.Flush();
compressedFileByes = memoryStream.ToArray();
}
}
//upload
var response = this.UploadFile(postURL, fileName, contentType, compressedFileByes);
//move file to new file
if (response.IsSuccessStatusCode)
{
string strUploadFile = Path.Combine(directoryPath, "UploadSuccess");
if (!Directory.Exists(strUploadFile))
Directory.CreateDirectory(strUploadFile);
string newFilePath = Path.Combine(strUploadFile, fileName);
try
{
string fileWithoutExt = Path.GetFileNameWithoutExtension(fileFullName);
string fileExtension = Path.GetExtension(fileFullName);
for (int i = 1; i < 100; i++)
{
if (!File.Exists(newFilePath))
break;
string newFileName = string.Format("{0} ({1}){2}", fileWithoutExt, i, fileExtension);
newFilePath = Path.Combine(strUploadFile, newFileName);
}
File.Move(fileFullName, newFilePath);
}
catch (Exception exMoveFile)
{
this.UploadLog(directoryPath, "Copy file failed. {0}, error: {1}", fileName, exMoveFile.Message);
}
this.UploadLog(directoryPath, "File Uploaded. " + fileName);
continue;
}
string errorMessage = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
if (errorMessage?.Length > 30)
errorMessage = errorMessage?.Substring(0, 30);
this.UploadLog(directoryPath, "File Upload failed. statusCode: {0}, file: {1}, msg: {2} ", response.StatusCode, fileName, errorMessage);
}
catch (Exception exx)
{
this.UploadLog(directoryPath, "File Upload failed. file: {0}, msg: {1} ", fileName, exx.Message);
}
}
//https://stackoverflow.com/questions/1131425/send-a-file-via-http-post-with-c-sharp
private HttpResponseMessage UploadFile(string actionUrl, string fileName, string fileType, byte[] paramFileBytes)
{
//HttpContent fileNameContent = new StringContent(fileName);
//HttpContent fileTypeContent = new StringContent(fileType);
HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
bytesContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
bytesContent.Headers.ContentLength = paramFileBytes.Length;
bytesContent.Headers.ContentType = new MediaTypeHeaderValue(fileType);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var formData = new MultipartFormDataContent())
{
//formData.Add(fileNameContent, "FileName");
//formData.Add(fileTypeContent, "FileType");
formData.Add(bytesContent, "fileData", fileName);
var response = client.PostAsync(actionUrl, formData).GetAwaiter().GetResult();
return response;
}
}
}
WebApi接收文件並解壓保存至數據庫
[HttpPost]
public IHttpActionResult UploadFile([Required][FromUri] string token)
{
if (token != WebConfig.Token)
return BadRequest("Token is incorrect");
var fileStream = HttpContext.Current.Request.Files[0].InputStream;
var fileName = HttpContext.Current.Request.Files[0].FileName;
var fileType = HttpContext.Current.Request.Files[0].ContentType;
byte[] decompressData = null;
using (var gzipStream = new GZipStream(fileStream, CompressionMode.Decompress))
{
using (var decompressMemory = new MemoryStream())
{
gzipStream.CopyTo(decompressMemory);
gzipStream.Flush();
decompressData = decompressMemory.ToArray();
}
}
this.Service.UploadToExcDocument(fileName, fileType, decompressData);
return Ok();
}
public void UploadToExcDocument(string fileName, string fileType, byte[] fileData)
{
string strSql = string.Empty;
//get DocumentID
var DocumentID = this.GetKey("DocumentID", this.DatabaseString);
strSql = @"
INSERT dbo.Document (DocumentName, DocumentSize, ContentType, DocumentDate, Description, DocumentID, DocumentData)
VALUES (@DocumentName, @DocumentSize, @ContentType, @NowDateTime, '', @DocumentID, @DocumentData);";
using (SqlConnection conn = new SqlConnection(this.DatabaseString))
{
conn.Execute(strSql, new { DocumentID, DocumentName = fileName, ContentType = fileType, DocumentSize = fileData.Length, DocumentData = fileData });
}
}