Angular 发送post请求并下载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类来重命名
<table mat-table [dataSource]="logDataSource" matSort class="mat-table">
<ng-container matColumnDef="Path">
<th mat-header-cell *matHeaderCellDef mat-sort-header> 路径 </th>
<td mat-cell *matCellDef="let element"> {{element.path}} </td>
</ng-container>
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef> 操作 </th>
<td mat-cell *matCellDef="let data">
<!--关键代码-->
<span (click)="downloadZip(data)">
<mat-icon>vertical_align_bottom</mat-icon>
</span>
<!--关键代码-->
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="logdisplayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: logdisplayedColumns;"></tr>
</table>
download(e) {
const token = localStorage. getItem(' token');
let headers: HttpHeaders = new HttpHeaders();
headers = headers.set(' Authorization', ' Bearer ' + token);
const url = 'http://localhost:8765/api/v1/oprator/archive';
this.http.post( url, {path:[e.path]}, {responseType: 'blob'}).subscribe(response => {
console.log(response);
console.log(response.headers.keys());
this.downloadFile(response,e.path);
},(error:HttpErrorResponse) => {
console.log(error.error);
});
}
downloadFile(data: any,path:string) {
let nameArr = path.split('/');
let name = nameArr[nameArr.length-1];
const file = new Blob([data], {type: 'application/zip'});
const a = document.createElement('a');
a.id = 'tempId';
document.body.appendChild(a);
a.download = `${name}_${moment().format(
"YYYY-MM-DD HH:mm:ss"
)}_日志.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
文章参考:https://blog.youkuaiyun.com/fanzhongli/article/details/84912057
总结:
一、通过post向后台发起请求
二、将返回的数据用new Blob进行包装,并设置{type: ‘application/zip’}
三、创建一个a标签并设置id属性便于之后移除
四、通过
a.download 设置下载后文件名
a.href = URL.createObjectURL(file);创建URL
a.click();
三步实现以zip格式自动下载返回的数据
五、移除a标签