reactjs - React + .net core api 中的下载文件问题
问题描述
我正在尝试在我的反应应用程序上实现文件下载,API 是一个 .net 核心 api。
我正在使用fileSaver js来实现前端,但它似乎没有正确保存文件。
我的 API:
[Authorize]
[HttpGet]
public async Task<IActionResult> DownloadInvoice(string ID)
{
var invoiceContent = await this.getfile(ID);
//this returns a byte array of the PDF file content
if (invoiceContent == null)
return NotFound();
var stream = new MemoryStream(invoiceContent); //saves it into a stream
stream.Position = 0;
return File(stream, "application/octec-stream", $"{invoiceNo}.pdf");
}
我的反应代码:
import { saveAs } from 'file-saver';
axios
.get(url, {
headers: {
'Content-Type': 'application/json',
responseType: 'blob',
},
})
.then(function(res) {
var blob = new Blob([res.data], {
type: 'application/pdf',
});
saveAs(blob, invoice.invoiceNo + '.pdf');
});
}}
我用邮递员测试了API,它返回正确的数据,我可以正确保存文件,
结果在邮递员中看起来像这样,这是 PDF 文件的正确内容:
%PDF-1.6
%����
1 0 obj
<<
/Creator(Telerik Reporting 7.1.13.612 \(http://www.telerik.com/products/reporting.aspx\))
/Producer(Telerik Reporting 7.1.13.612 \(http://www.telerik.com/products/reporting.aspx\))
/CreationDate(D:20190124112008+13'00')
>>
endobj
2 0 obj
<<
/Type/Catalog
/ViewerPreferences 3 0 R
/Pages 4 0 R
>>
endobj
3 0 obj
[bla bla bla....]
但是当它在反应中通过blob保存时,它会创建一个带有空白页的“有效”pdf文件。文件大小增加(从 43k 到 76k)..
我想知道是否有人知道这个实现有什么问题,并能指出我正确的方向。
非常感谢
解决方案
好的,问题是这样的:
.get(url, {
headers: {
'Content-Type': 'application/json',
},
responseType: 'blob', ////move this line out of the headers....
})
推荐阅读
- shell - 暂停在终端屏幕中运行的脚本?
- sql - SQL Server - 计算包含 YYYY-MM-DD HH:MM:SS 格式的日期时间戳的多列之间的经过时间
- php - PHP 无法访问此对象的值
- cuda - 我可以用 cuda 找到价格地板和天花板吗
- ibm-information-server - IIS Metadata Asset Manager v11.5 是否支持 SQL Server v2014 报告服务 (SSRS 2014)
- java - 手动获取类信息(例如字段或返回类型)
- configuration - 如何使用 Spring Cloud 在一个 Spring Boot 应用程序中连接/配置两个 pubsub gcp 项目?
- python - 子集熊猫数据框并在一行中分配不同的列
- postgresql - postgresql 存储过程可以在单独的数据库上运行吗?
- javascript - DateTime whout seconds React highcharts