代码之家  ›  专栏  ›  技术社区  ›  Martijn van den Bergh

如何使用新的HttpClient下载文件?

  •  0
  • Martijn van den Bergh  · 技术社区  · 7 年前

    const subscription = this.downloadService.downloadFile(id, this.file.folderId).subscribe(data => {
        window.location.href = data.url;
        subscription.unsubscribe();
    });
    

    Chrome会自动下载文件并留在网站上。

    现在我要做的是:

    const subscription = this.downloadFile(id, folderId).subscribe(data => {
        const blob = new Blob([data], { type: 'image' });
        const blobUrl = window.URL.createObjectURL(blob);
        window.location.href = blobUrl;
        subscription.unsubscribe();  
    });
    

    Chrome也会开始下载,但始终是同一个文件,在控制台中如下所示:

    enter image description here

    const file = new File([blob], name, { lastModified: Date.now(), type: 'image' })
    

    我需要如何处理这些数据以确保它以图像的形式下载(我总是尝试下载图像)?

    const httpParams = new HttpParams();
    httpParams.append('action', 'downloadFile');
    httpParams.append('fileIds', id.toString());
    httpParams.append('currentLibraryFolderId', folderId.toString());
    

    只传递了一个空的httpParams。这是正确的方法:

    const params = new HttpParams()
        .set('action', 'downloadFile')
        .set('fileIds', id.toString())
        .set('currentLibraryFolderId', folderId.toString());
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Akj    7 年前

    尝试 window.open(url)

    如果类型是浏览器支持的,比如 image pdf 打开或者下载。

    HTML格式:

    <a (click)="downloadFile(fileData, type)" download>Download File</a>
    

    FileSaver :

     npm install file-saver --save
    
     import { saveAs } from 'file-saver/FileSaver';
    

    如果你得到的回应是 arraybuffer

    var blob = new Blob([data], { type: type});
    
    var url = window.URL.createObjectURL(blob);
    
    saveAs(blob, filename);
    
    var winOpen = window.open(url);
    
    
    // If Popup blocked
    if (!winOpen || winOpen.closed || typeof winOpen.closed == 'undefined') {
           alert( 'Please disable your Pop-up blocker and try again.');
     }
    
    推荐文章