Angular 下载zip文件并重命名文件

后端Java代码需要设置response的header,如下

 

response.setContentType("application/octet-stream; charset=utf8");
response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename="+zipName);

Angular/Typescript需要使用File类来重命名

download() {
const token = localStorage. getItem(' token');
let headers: HttpHeaders = new HttpHeaders();
headers = headers
. set(' Authorization', ' Bearer ' + token);
const url = 'http://localhost:8764/api/v1/user/downLoadZipFile';
this. http. get( url, {headers: headers, observe: ' response', responseType: ' blob'}). subscribe( response => {
console. log( response);
console. log( response.headers. keys());
this. downloadFile( response);
}, ( error: HttpErrorResponse) => {
console. log( error. error);
});
}

downloadFile( data: HttpResponse< Blob>) {
const file = new Blob([ data.body], {type: ' application/zip'});
const a = document. createElement(' a');
a.id = ' tempId';
document.body. appendChild( a);
a. download = ' haha.zip';
a.href = URL. createObjectURL( file);
a. click();
const tempA = document. getElementById(' tempId');
if ( tempA) {
tempA.parentNode. removeChild( tempA);
}
 
}
}
 
   

 关于File类,可以参考以下文档

 

 

 

https://developer.mozilla.org/zh-CN/docs/Web/API/File

 

 

 

 

你可能感兴趣的:(Angular 下载zip文件并重命名文件)