c# - 使用 asp.net core 2.1 在 angular 8 中下载文件总是会给出损坏的文件
问题描述
我在我的项目中使用asp.net core 2.1,客户端使用angular 8,但无法为downolad文件制作功能,下载时只能下载.txt文件,无法下载.pdf,.excell,image等。下面是我的代码。
downloadFiles(filename: any) {
return this.http.get(this.myAppUrl + 'api/Download/' + filename)
.catch(this.errorHandler)
}
//after getting response data from server and passing to the method makeDownloadFiles only
//downloded corrupted file.
makeDownloadFiles(data: any) {
debugger;
const blob = new Blob([data]);
const url = window.URL.createObjectURL(blob);
window.open(url);
}
//and server code is
[HttpGet]
[Route("api/Download/{filename}")]
public FileResult Download(string filename){
try {
string extension = filename.Substring(filename.IndexOf('.') + 1);
string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/files", filename);
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
string fileName = filename;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
} catch (Exception ex){
return null;
}
}
解决方案
一旦我在调用中指定类型get
并且对new Blob
您的代码的调用工作正常:
downloadFiles(filename: any) {
return this.http.get(this.myAppUrl + 'api/Download/' + filename, { responseType: 'blob'})
.catch(this.errorHandler)
}
makeDownloadFiles(data: any) {
debugger;
const blob = new Blob([<any>data], {type: 'application/octet-stream'});
const url = window.URL.createObjectURL(blob);
window.open(url);
}
推荐阅读
- visual-studio - 如何制作表格和代码以仅显示每 1 个实体数据的 1 个报告?
- delphi - Delphi android以编程方式显示组合框列表
- c# - 从类中获取 INT 值
- vhdl - vhdl 不能切片记录
- java - 如何从另一个方法访问方法的返回类型
- c3.js - 如何隐藏视图中的列(数字)数据?
- image - React Native 背景图像 - 覆盖和垂直对齐到顶部
- string - Umbraco Razor,比较字符串中的两组页面 ID 是否匹配
- java - JPA 和 1000 ID 在 Oracle IN 运算符中的使用
- command-line - aerender 完成后未退出