【问题标题】:Angular 5 How to download a remote imageAngular 5 如何下载远程图像
【发布时间】:2019-02-01 20:03:30
【问题描述】:

在 Angular 5 中,我想从 localhost(服务器)下载图像。我已经有了路径为的图像名称:http://localhost/projectName/uploads/3/1535352341_download.png 现在我想通过点击一个按钮来下载。

在 Angular 的 HTML 视图中,我编写了以下代码:

<button (click)="downloadImage(car.carItem.carTitle)" type="button" class="btn btn-sm btn-info btn-action" tooltip="Download Image" placement="left" container="body"><i class="fa fa-download" aria-hidden="true"></i></button>

在 .ts 文件中,我执行以下操作,但它会在同一选项卡中打开图像:

downloadImage(imagePath){
  window.location = imagePath;
}

我已经浏览了Angular 4 direct download images 的帖子,但找不到任何解决方案。所以请不要将其标记为重复。

【问题讨论】:

    标签: angular angular5


    【解决方案1】:

    由于您的图像位于远程服务器上,出于安全原因,您不能像使用自己的资源一样简单地下载它。

    这是一个简单的 downloadUrl 函数,它会要求浏览器下载任何给定的 url:

        function downloadUrl(url: string, fileName: string) {
          const a: any = document.createElement('a');
          a.href = url;
          a.download = fileName;
          document.body.appendChild(a);
          a.style = 'display: none';
          a.click();
          a.remove();
        };
    

    由于我们无法下载远程资源,我们将不得不在客户端构建它。 我们将获取资源并创建它自己的 url。然后我们终于可以使用我们的downloadUrl 函数下载它了。

        constructor(
          private http: HttpClient,
        ) { }
    
    -------
        this.http.get(urlImage, { responseType: 'blob' }).subscribe(val => {
          console.log(val);
          const url = URL.createObjectURL(val);
          downloadUrl(url, 'image.png');
          URL.revokeObjectURL(url);
        });
    

    【讨论】:

    • 它在同一个标​​签中打开图像!
    • “在同一选项卡中打开”是什么意思。您要求下载它,而不是打开它。
    • 好吧,我刚刚找到了解决办法,我们来写吧。
    • 请相应地编辑您的问题:“如何下载远程图像”
    • 那是你后端的问题,这是另一个问题。您需要允许您的应用程序对您的图像进行跨源请求。
    【解决方案2】:
    <a href=" http://localhost/projectName/uploads/3/1535352341_download.png" class="btn clss"
                      target="_self" download>Download</a>
    

    【讨论】:

    • 虽然此代码 sn-p 可能是解决方案,但包含解释确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    • 该解决方案甚至不起作用,它只是在同一选项卡中的浏览器上打开图像。
    【解决方案3】:

    感谢@Ploppy 引导我朝着正确的方向前进,

    这是我的解决方案,使用 fetch (TypeScript) 并绕过 cors

    const getExternalImageFromURL = (requesturl: string): Promise<Blob> => {
        const proxyurl = "https://cors-anywhere.herokuapp.com/";
    
        return fetch(proxyurl + requesturl).then((res) => {
            return res.blob();
        });
    };
    
    【解决方案4】:
      constructor(private rs: RequestService,
          private http: Http,
          private sanitizer: DomSanitizer) {
      }
    
      getImage(imageUrl: string) {
          return this.http
                     .get(imageUrl, {responseType: ResponseContentType.Blob})
                     .map((res) => {
                         return new Blob([res.blob()], {type: res.headers.get('Content-Type')});
                     });
      }
    
      downloadImage(downloadLink) {
          this.orderService
              .getImage(downloadLink)
              .subscribe(
                  (res) => {
                      const a = document.createElement('a');
                      a.href = URL.createObjectURL(res);
                      a.download = 'comprobante';
                      document.body.appendChild(a);
                      a.click();
                  });
      }
    

    【讨论】:

      【解决方案5】:

      只要你需要在你的应用程序中执行 CORS,那么在服务器端必须有一些机制来只允许指定的跨站点请求,所以下面的 sn-p 是针对 NodeJs 的

      let middle_ware = (req, res, next) => next();
      ...
      return function (req, res, next) {
          const allowed_Origins = ['http://any_url.com'];
          const origin = req.headers.origin;
          if (allowed_Origins.includes(origin)) {
            res.header('Access-Control-Allow-Origin', origin);
          }
          res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
          res.header({
            HttpOnly: true,
            Secure: true,
            SameSite: 'None',
          });
          middle_ware(req, res, next);
        };
      

      如果您使用的是 PHP,我希望在 PHP 中这可能对您有所帮助 Cross-Origin Request Headers(CORS) with PHP headers 谢谢!

      【讨论】:

        【解决方案6】:

        我使用 SaveAs 从 unsplash 下载图像。

        步骤 1。安装

        npm i 角度文件保护程序

        步骤 2。将其导入您的组件 从 'file-saver/FileSaver' 导入 { saveAs };

        第 3 步。以图片url为参数调用函数

        download(url){
            this.http.get(url,{ responseType: 'blob' }).subscribe(
              (d:any)=>{
                console.log("image url data",d);
                saveAs(d, "image.jpg");
            
              },
              (err:any)=>{
                console.log("error",err)
              }
            )
          
          }
        

        【讨论】:

          猜你喜欢
          • 2019-01-24
          • 2011-01-10
          • 1970-01-01
          • 1970-01-01
          • 2014-10-28
          • 1970-01-01
          • 1970-01-01
          • 2016-04-30
          • 2011-11-02
          相关资源
          最近更新 更多