Javascript/Angular 调用AWS安全链接下载文件仅返回1KB问题
问题修复方案
核心原因
- 调用
awsService.downloadFile请求文件时,未指定HTTP响应类型为blob,框架默认会将响应解析为JSON格式,返回结果并非原始二进制文件流 - 原有代码错误访问了
data.Body属性,当响应类型正确设置为blob时,返回的data本身就是Blob对象,不存在Body子属性,取空值生成的Blob自然只有1KB大小
修复步骤
第一步:调整downloadFile请求配置
修改awsService中的downloadFile方法,明确指定响应类型为blob,Angular场景示例:
// aws.service.ts 中的downloadFile方法 downloadFile(url: string) { // 新增responseType: 'blob'配置,告诉框架返回原始二进制流 return this.http.get(url, { responseType: 'blob' }); }
第二步:修正下载逻辑代码
移除不存在的data.Body调用,直接使用返回的Blob对象,同时补充内存释放逻辑:
downloadFile(file: string) { this.awsService .getDownloadUrl(file, poNumber, client) .pipe(takeUntil(this.unsubscribe)) .subscribe(resp => { if (resp && resp.url) { this.awsService.downloadFile(resp.url).subscribe(data => { const navigator = this.window.navigator; const isIE = /msie\s|trident\//i.test(navigator.userAgent); if (isIE) { navigator.msSaveOrOpenBlob(data, file); } else { const blob = new Blob([data], { type: data.type }); const link = document.createElement('a'); link.href = this.window['URL'].createObjectURL(blob); link.download = file; link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: this.window })); // 用完释放URL对象,避免内存泄漏 window.URL.revokeObjectURL(link.href); } }); } }); }
更优方案
AWS返回的安全链接是预签名下载URL,本身支持直接访问下载,不需要额外发起一次HTTP请求转Blob,可直接简化代码:
downloadFile(file: string) { this.awsService .getDownloadUrl(file, poNumber, client) .pipe(takeUntil(this.unsubscribe)) .subscribe(resp => { if (resp && resp.url) { const link = document.createElement('a'); link.href = resp.url; link.download = file; link.target = '_blank'; link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: this.window })); } }); }
内容的提问来源于stack exchange,提问作者dcp3450
相关产品推荐
相关产品推荐

