【问题标题】:Custom file name of file to download in Angular 2要在 Angular 2 中下载的文件的自定义文件名
【发布时间】:2018-08-12 20:05:50
【问题描述】:

我正在尝试从任何 url 下载具有自定义名称的文件。

我正在我的代码上尝试这个

downloadAttachment(attachment) {
    var a = document.createElement('a');
    a.href = attachment.url; //URL FOR DOWNLOADING
    a.download = 'CustomName.png';
    a.click();
}

从视图上看是<button (click)="downloadAttachment(attachment)"></button>

它正在下载文件,但仍然从 url 中获取文件名。

如何为文件添加自定义名称?

【问题讨论】:

  • 那么问题是什么?
  • 如何给文件添加自定义名称?
  • 我提到它'CustomName.png'
  • 我稍后会提供一个有意义的全名,我只需要让自定义名称成为可能

标签: angular typescript download


【解决方案1】:

如果 HTTP 标头 Content-Disposition: 存在并给出 与此属性不同的文件名,HTTP 标头具有优先权 在这个属性上。

检查响应标头。

Chrome Download Attribute not working

因此,如果可能,您将不得不更改存储文件的后端。

编辑: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a

此属性仅适用于指向同源资源的链接。

编辑2:

getImage(imageUrl: string): Observable<File> {
    return this.http
        .get(imageUrl, { responseType: ResponseContentType.Blob })
        .map((res: Response) => res.blob());
}

现在您的内存中有一个文件,您可以随意保存它。

【讨论】:

  • 文件存储在s3中
  • 下载文件时检查网络中的响应头并找到 Content-Discposition 属性。如果它在那里,您将无法真正完成您的要求。
  • 响应标头没有 Content-disposition,我将研究 aws s3 如何添加 cusotm 标头,然后添加“Content-Disposition: inline”并检查。
  • 现在似乎对我来说最好的选择是将文件以所需名称保存在 s3 上,最好支持所有浏览器
  • 我猜。您也可以将文件下载为 Base64 并根据需要保存。再次检查编辑。
【解决方案2】:

使用 http.get:

下载文件
    let queryApi = someApi
    this.http.get(queryApi, { responseType: 'blob', observe: 'response' })
        .subscribe(respone => {

            // file-type
            let fileName = 'custom-file-name.fileExt';             

            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(respone.body);
            link.download = fileName;
            link.click();
        });     

【讨论】:

    【解决方案3】:

    这样使用

    <a [href]=URLoftheFile download="FilenameWithExtension">DownloadFile</a>
    

    但不适用于跨域

    【讨论】:

      猜你喜欢
      • 2018-05-30
      • 1970-01-01
      • 2017-11-10
      • 2017-08-05
      • 2018-03-06
      • 2018-04-12
      • 2018-01-01
      • 2017-01-01
      • 2021-03-31
      相关资源
      最近更新 更多