.net core 接收並存儲客戶端上傳的檔案
阿新 • • 發佈:2022-02-15
1 檔案是上傳到Host,非上傳到阿里雲OSS
2 在Program.cs或StartUp中使用靜態檔案的中介軟體
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseStaticFiles(); }
.net core 建立的api專案中,會有一個wwwroot資料夾,在wwwroot資料夾我們建立一個image資料夾,image資料夾中有一個圖片a.jpg,當中間件UseStaticFiles啟用後,我們可以通過在瀏覽器上輸入[ip]:[port]/image/a.jpg成功瀏覽圖片。
3 具體代[HttpPost("UploadInvoiceFile")]
public async Task<IActionResult> UploadFile(IFormFile file) { if (!new[] {"image/jpeg", "image/png", "application/pdf"}.Contains(file.ContentType)) return BadRequest("圖片僅支援jpg和png格式,檔案支援pdf"); if (file is {Length: > 0}) try { var fileName = Path.GetFileName(file.FileName); var staticFileRoot = "wwwroot"; // 這裡是檔案路徑,不包含檔名 var fileUrlWithoutFileName = @$"InvoiceStaticFile\{DateTime.Now.Year}\{DateTime.Now.Month}\{DateTime.Now.Day}"; // 建立資料夾,如果資料夾已存在,則什麼也不做 Directory.CreateDirectory($"{staticFileRoot}/{fileUrlWithoutFileName}"); //string fileName = Path.GetFileName(postedFile.FileName); //using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create)) //{ // postedFile.CopyTo(stream); // uploadedFiles.Add(fileName); // ViewBag.Message += string.Format("<b>{0}</b> uploaded.<br />", fileName); //}
// 使用雜湊的原因是前端可能傳遞相同的檔案,服務端不想儲存多個相同的檔案
var hash = SHA256.Create(); // 讀取檔案的流 把檔案流轉為雜湊值 var hashByte = await hash.ComputeHashAsync(file.OpenReadStream()); // 再把雜湊值轉為字串 當作檔案的檔名 var hashedFileName = BitConverter.ToString(hashByte).Replace("-", ""); // 重新獲得一個檔名 var newFileName = hashedFileName + "." + fileName.Split('.').Last(); var filePath = Path.Combine(Directory.GetCurrentDirectory(), $@"{staticFileRoot}\{fileUrlWithoutFileName}", newFileName); await using var fileStream = new FileStream(filePath, FileMode.Create); await file.CopyToAsync(fileStream); return Created("", new {Name = fileName, Url = Path.Combine(fileUrlWithoutFileName, newFileName)}); } catch (Exception e) { _logger.LogError(e, "儲存檔案出錯。錯誤訊息:" + e.Message); throw; } return BadRequest("請上傳檔案"); }