我从 WebAPI
返回一个文件 Controller 。 Content-Disposition
header 值会自动填充,它还包含我的文件名。
我的后端代码如下所示:
[HttpGet("Download")]
public async Task<ActionResult> Download([FromQuery]CompanySearchObject req)
{
string fileName = "SomeFileName_" + DateTime.UtcNow.Date.ToShortDateString() + ".csv";
var result = await _myService.GetData(req);
Stream stream = new System.IO.MemoryStream(result);
return File(stream, "text/csv", fileName.ToString());
}
在我的前端:
exportData(params).then(response => {
console.log(response);
console.log('Response Headers:', response.headers);
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type, encoding: 'UTF-8' });
//const filename = response.headers['content-disposition'].split('"')[1];
//alert(filename);
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'file.xlsx';
link.click();
link.remove();
});
};
但我正在努力获取这些数据,因为当我在前端执行 console.log 时,我看不到这个.. 如你所见,我记录了响应
console.log('Response Headers:', response.headers);
但我唯一看到的是:这些数据不应该在某个地方吗?我想知道如何从
Content-Disposition
读取值并获取文件名?多谢你们
干杯
最佳答案
有同样的问题。我的问题是CORS。如果您正在使用它,则需要在配置中像这样公开它:
app.UseCors(builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyMethod();
builder.AllowAnyHeader();
builder.WithExposedHeaders("Content-Disposition"); // this is the important line
});
关于javascript - 从 ASP.NET CORE Web Api 获取 React 中的特定响应 header (例如,Content-Disposition),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57621848/