作者:夕阳红梅乎 | 来源:互联网 | 2022-12-07 04:09
以下是我的Typescript代码,可从API下载文件
DownloadLM() {
var ID= sessionStorage.getItem("UserID");
return this.http.get(this.baseurl + 'api/DownloadFiles/DownloadLM/' + ID,
{
headers: {
'Content-Type': 'application/json'
},
responseType: 'arraybuffer'
}
)
.subscribe(respData => {
this.downLoad(respData, this.type);
}, error => {
});
}
downLoad(data: any, type: string) {
var blob = new Blob([data], { type: type.toString() });
var url = window.URL.createObjectURL(blob);
var pwa = window.open(url);
if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
alert('Please disable your Pop-up blocker and try again.');
}
}
下载Excel文件很好,但是它给我不需要的文件一个随机的名字,我要在下载时设置自己选择的文件名,
在哪里可以设置文件名?Blob的任何属性?
1> Sajeetharan..:
您可以将download属性设置为所需的文件名,将href设置为对象url,然后调用
var blob = new Blob([data], { type: type.toString() });
var url = window.URL.createObjectURL(blob);
var anchor = document.createElement("a");
anchor.download = "myfile.txt";
anchor.href = blobURL;
anchor.click();
2> Dhivakaran R..:
如果您想要上传文件的确切文件名,请从支持的API流中设置文件名的自定义标头。
您可以像这样使用它:我的Excel API响应标头:
content-disposition: inline;filename="salesReport.xls"
content-type: application/octet-stream
date: Wed, 22 Aug 2018 06:47:28 GMT
expires: 0
file-name: salesReport.xls
pragma: no-cache
transfer-encoding: chunked
x-application-context: application:8080
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
服务
content-disposition: inline;filename="salesReport.xls"
content-type: application/octet-stream
date: Wed, 22 Aug 2018 06:47:28 GMT
expires: 0
file-name: salesReport.xls
pragma: no-cache
transfer-encoding: chunked
x-application-context: application:8080
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
Component.ts
excel(data: any) {
return this.httpClient.post(this.config.domain +
`/api/registration/excel/download`,data, {observe: 'response', responseType: 'blob'})
.map((res) => {
let data = {
image: new Blob([res.body], {type: res.headers.get('Content-Type')}),
filename: res.headers.get('File-Name')
}
return data ;
}).catch((err) => {
return Observable.throw(err);
});
}