我需要下载一个 ZIP 文件并将该文件的链接放入我的应用程序中,以便用户可以单击它。
当前代码:
服务:
public downloadFileWithAuthorization(urlOfFile: string, user: string, password: string) : Observable<any> {
let headerParams: HttpHeaders = new HttpHeaders({
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + btoa(user + ":" + password),
});
return this.http.get(urlOfFile, {
reportProgress: false,
observe: "events",
headers: headerParams,
responseType: "blob"
})
}
生成的 BLOB 应存储在具有一些附加值的实体中:
export class URLEntity {
path?: string;
name?: string;
fileContent?: any;
fileUrl?: string;
}
下载并分配给 zipFile[0] 后,我使用 createObjectUrl 创建指向它的链接:
getDownloadFile() {
this.downloadFileSub = this.downloadService.downloadFileWithAuthorization( this.emailMessage!.downloadURL![0].path!, this.user, this.password).subscribe(
{
next: value => {
this.zipFile[0].fileContent = value.body;
this.zipFile[0].fileUrl = window.URL.createObjectURL(this.zipFile[0].fileContent);
},
error: err => {
new ErrorMessage(err.message, this.messageService).provide();
}
}
);
}
并使用 ngFor 以 HTML 形式显示,因为从另一个代码部分可以为同一视图提供多个文件:
<div *ngFor="let urlentity of zipFile">
<button pButton pRipple icon="p-button-icon pi pi-file-edit" link="true"
class="p-button-rounded p-button-success mr-2">
<a href="{{urlentity.fileUrl}}" target="_blank" rel="noopener noreferrer">{{urlentity.name}}</a>
</button>
</div>
我现在的问题是,这通常有效,我可以下载并打开 ZIP 文件。但是,在控制台中出现错误:
无法在“URL”上执行“createObjectURL”:重载解析失败。
好像是这条线
this.zipFile[0].fileUrl = window.URL.createObjectURL(this.zipFile[0].fileContent);
不正确。知道如何解决吗?
您可以将响应转换为 blob,然后将其传递给
createObjectURL
,这似乎可行。
downloadFile() {
this.appSvc.getFile({ SomeData: '' }).subscribe((data) => {
const blob = new Blob([data], { type: 'application/zip' });
const url = window.URL.createObjectURL(blob);
window.open(url);
});
}