angular - 使用 Angular 2 和 .Net Core API 下载文件
问题描述
我有一个 WebAPI,它有一个制作 Excel 文件并使用File()
.
在我的 Angular 应用程序中,我订阅了响应并使用 blob 下载文件。但是我在浏览器控制台中收到一个错误,它说它无法解析对 JSON 的响应。
为什么要解析对 JSON 的响应?以及如何解决这个问题?
API 控制器:
[HttpPost]
public IActionResult QRGenerator(QRCode qrCode)
{
string wwwrootPath = _hostingEnvironment.WebRootPath;
var QrCodes = new List<QRCode>();
QrCodes.Add(qrCode);
ExcelGenerator generator = new ExcelGenerator();
var fileName = generator.GeneratePrintableSheets(QrCodes, wwwrootPath);
var path = Path.Combine(wwwrootPath, fileName);
return DownloadFile(fileName, wwwrootPath);
}
public IActionResult DownloadFile(string fileName, string wwwrootPath)
{
var path = Path.Combine(wwwrootPath, fileName);
var content = System.IO.File.ReadAllBytes(path);
return File(content, "application/vnd.ms-excel", fileName);
}
角组件:
createQR(qrCode: QRCode) {
let formData: FormData = new FormData();
this.singleQr.CreateSingleQR(formData).subscribe(data => {
this.downloadFile(data);
console.log(data);
});
}
downloadFile(data: any){
var blob = new Blob([data], { type: 'application/vnd.ms-excel' });
var url= window.URL.createObjectURL(blob);
window.open(url);
}
为了完成,Angular 服务:
CreateSingleQR(formdata: FormData) {
return this.http.post(this.qrUrl, formdata);
}
解决方案
您需要告诉Angular
响应不是JSON
,因此它不会尝试解析它。尝试将您的CreateSingleQR
代码更改为:
CreateSingleQR(formdata: FormData) {
return this.http.post(this.qrUrl, formdata, { responseType: ResponseContentType.Blob } );
}
推荐阅读
- java - android项目文件中的许多文件
- java - Springboot测试如何将控制器的参数解析为对象
- javascript - 根据多个条件过滤对象的JSON数组
- javascript - 为什么 element.attribute 在 Edge 中不起作用?
- feathersjs - 如何使用服务仅处理而不存储在 FeathersJS 中
- javascript - 如何正确创建包含多个类的模块的入口点?
- xamarin - 在 Xamarin 中弹出加载?
- javascript - 是什么导致 eventSource 保持在 readyState 0?
- ios - 创建圆角时如何添加边框UITextField Swift
- hibernate - 我们什么时候需要 .save() Spring 中的实体?