目前我們完成檔案上傳的功能,接下來就要進行檔案下載
寫一個專門下載檔案的Action,接受ID參數,去資料庫看目錄中有沒有這個檔案,有的話就去檔案存放資料夾將檔案傳給Client。
public async Task<IActionResult> Get(Guid id)
{
var fileData = _context.File.Find(id.ToString());
if (fileData == null)
{
return NotFound();
}
var path = $"data/{fileData.Name}";
var memoryStream = new MemoryStream();
await using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memoryStream);
}
memoryStream.Seek(0, SeekOrigin.Begin);
var contentTypes = new Dictionary<string, string>
{
{".png", "image/png"},
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".gif", "image/gif"}
};
// 要跟前端說要下載檔案的類型
return new FileStreamResult(
memoryStream,contentTypes[Path.GetExtension(path).ToLowerInvariant()]);
}