.NET6 Web Api 檔案下載同時取得檔名
.NET6, Download File, Content-Disposition, ContentDisposition
引言
主要參考文章
下載檔案同時送回檔名:Content-Disposition

程式碼紀錄
Last updated
.NET6, Download File, Content-Disposition, ContentDisposition

Last updated
Content-Disposition: attachment; filename="theFileName.ext"using Microsoft.AspNetCore.Mvc;
namespace YourProject.Controllers;
[ApiController]
[Route("api/[controller]/[action]")]
public class FileController : ControllerBase
{
[HttpPost]
public IActionResult DownloadFile()
{
FileInfo fi = new FileInfo(@"Template/MinIO 評估.docx");
byte[] blob = System.IO.File.ReadAllBytes(fi.FullName);
return File(blob, System.Net.Mime.MediaTypeNames.Application.Octet, fi.Name);
//※ 其中 FileContentResult 第3個參數會產生 Content-Disposition 的 Response Header 把檔名編碼後送到前端。
}
}import { saveAs } from 'file-saver'
function handleDownloadFile() {
const url = 'api/File/DownloadFile'
const options = {
method: 'POST',
};
let fileName = 'unknown.bin'
fetch(url, options)
.then(resp => {
if (!resp.ok) throw new Error('Network response was not ok.');
// 解析附件檔名
const contentDisposition = resp.headers.get('content-disposition') as string
fileName = decodeURI(contentDisposition.split("filename*=UTF-8''")[1])
return resp.blob();
})
.then(blob => {
saveAs(blob, fileName)
});
}var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
options.AddDefaultPolicy(policy =>
policy.WithExposedHeaders("Content-Disposition")
//※ 讓 FileContentResult 可以回傳檔名。預設被過濾掉。
));
...省略...
var app = builder.Build();
...省略...
app.UseRouting();
app.UseCors();
...省略...