【问题标题】:Download image from url in Angular 5从 Angular 5 中的 url 下载图像
【发布时间】:2019-01-24 16:48:12
【问题描述】:

我有一个 URL,其中包含我需要下载的图像。 我想制作一个按钮来下载它。 我尝试了这两个选项:

    const a = document.createElement('a');
        a.href = ImageURL;
        a.download = title;
        document.body.appendChild(a);
        a.click();

     window.location.href = t;

但这两个选项都只是打开一个带有图像的新窗口。

有没有一种方法可以代替刚刚下载文件的新窗口?

【问题讨论】:

  • 图片是否来自同一个域?
  • 不,它来自 CARTO 的一个 url,即静态图像 API。

标签: angular image url download


【解决方案1】:

这不是角度问题。您只能使用download 属性来强制下载图像/文件,如果:

  • 服务器还说应该下载它,或者
  • 图片来自同一个域。

这是跨域href的问题。

https://stackoverflow.com/a/17527821/4899523

https://stackoverflow.com/a/49736875/4899523

【讨论】:

    【解决方案2】:

    您可以尝试在HTML 中添加download 属性,例如

    <a href="IMAGE_URL" download="imagename.png">
    

    但据我所知,新浏览器有一些限制。

    【讨论】:

      【解决方案3】:

      这是一个使用 javascript 的实现,它需要使用 IE、Firefox 和 Chrome 从 URL 下载图像。有必要使用 httpclient 将图像作为 Blob 获取,然后在 DOM 中创建一个元素并模拟单击该元素以强制浏览器下载图像。

      HTML:

          <img src="IMAGE_URL" #img>
          <a href="javascript:void(0);" (click)="downloadImage(img)">Download</a>
      

      打字稿:

          constructor(private httpClient: HttpClient) {
          }
          
          downloadImage(img) {
             const imgUrl = img.src;
             const imgName = imgUrl.substr(imgUrl.lastIndexOf('/') + 1);
             this.httpClient.get(imgUrl, {responseType: 'blob' as 'json'})
               .subscribe((res: any) => {
                 const file = new Blob([res], {type: res.type});
      
                 // IE
                 if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                   window.navigator.msSaveOrOpenBlob(file);
                   return;
                 }
      
                 const blob = window.URL.createObjectURL(file);
                 const link = document.createElement('a');
                 link.href = blob;
                 link.download = imgName;
      
                 // Version link.click() to work at firefox
                 link.dispatchEvent(new MouseEvent('click', {
                   bubbles: true,
                   cancelable: true,
                   view: window
                 }));
      
                 setTimeout(() => { // firefox
                   window.URL.revokeObjectURL(blob);
                   link.remove();
                 }, 100);
               });
           }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-06
        • 2019-02-01
        • 1970-01-01
        • 2014-10-27
        • 1970-01-01
        • 2017-06-12
        • 2015-10-01
        • 2021-03-30
        相关资源
        最近更新 更多