下面是我的打字稿代码下载文件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文件,但它提供了一个随机的名字,而我不想,我想设置我的选择的文件名,下载时文件,
我在哪里可以设置文件名吗?斑点的任何财产?
如果你想上传的文件的确切的文件名,设置从备份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
Service.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);
});
}
Component.ts
excelDownload (data) {
this.registration.excel(data).subscribe(
(res) => {
const element = document.createElement('a');
element.href = URL.createObjectURL(res.image);
element.download = res.filename;
document.body.appendChild(element);
element.click();
this.toastr.success("Excel generated successfully");
},
(error) =>{
this.toastr.error('Data Not Found');
});
}
您可以设置下载属性到你想要的文件名,设置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();