我正在尝试使用angular 2和net core 2作为API来下载一个文件。
当用户单击下载链接时,他们应该能够将文件保存在本地计算机中。
我之前看过的每一个答案都有很大的不同,我似乎不能理解/让他们工作。
不管怎样,这就是我在服务器上得到的,我返回一个文件流
var content = System.IO.File.ReadAllBytes(tempFilename);
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var fileName = "test.xlsx";
return File(content, contentType, fileName);返回的流是正常的。现在我的理解是,我必须在客户端创建一个blob?然后读取并保存blob或其他什么?
目前,在我的客户端上,我有一个get请求返回一个observable。
下面是对我的服务的组件调用:
this.reportService.generateDispensations(this.config).subscribe(data => {
});我真的不确定在实际的http调用中应该修改什么,以将其转换为blob或其他什么。
发布于 2018-02-22 22:21:29
为了快速解决问题,如果您的文件不需要身份验证,您可以这样做
const url = `${environment.apiUrl}/location/to/download/from`
window.location.href = url;发布于 2019-11-13 18:09:02
假设你有数据文件在某个文件夹中,比如wwwroot文件夹中的"image“文件夹。假设您在图像文件夹中有文件名abc.jpg。要获取此文件,请在html组件中编写以下代码。
<a href="https://localhost:8438/image/abc.jpg" target="_blank" ><i class="fa fa-download"></i></a>使用您的删除基URL。
或者你可以在component.ts中使用下面的方法,fileNameUrl是图片的完整url。
DownLoadFilesUrl(fileNameUrl: any) {
debugger;
var filename: string[] = fileNameUrl.split('\\');
this.getBlobFile(fileNameUrl).subscribe((data: Blob) => {
debugger;
let item = filename[filename.length - 1];
let checkFileType = item.split('.').pop();
var fileType: any;
if (checkFileType == "txt") {
fileType = "text/plain";
}
if (checkFileType == "pdf") {
fileType = "application/pdf";
}
if (checkFileType == "doc") {
fileType = "application/vnd.ms-word";
}
if (checkFileType == "docx") {
fileType = "application/vnd.ms-word";
}
if (checkFileType == "xls") {
fileType = "application/vnd.ms-excel";
}
if (checkFileType == "xlsx") {
fileType = "application/vnd.ms-excel";
}
if (checkFileType == "png") {
fileType = "image/png";
}
if (checkFileType == "jpg") {
fileType = "image/jpeg";
}
if (checkFileType == "jpeg") {
fileType = "image/jpeg";
}
if (checkFileType == "gif") {
fileType = "image/gif";
}
if (checkFileType == "csv") {
fileType = "text/csv";
}
if (checkFileType == "amr") {
fileType = "AMR-WB";
}
var blob = new Blob([data], { type: fileType })
const blob1: Blob = data;
const fileName1: string = item;
const objectUrl: string = URL.createObjectURL(blob);
const a: HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;
a.href = objectUrl;
a.download = fileName1;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(objectUrl);
});
}
getBlobFile(imageUrl: string): Observable<Blob> {
return this._http.get(imageUrl, { responseType: 'blob' });
}https://stackoverflow.com/questions/48928172
复制相似问题