Angular 下载zip文件

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标签

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值