【问题标题】:Download file from server Angular 2从服务器 Angular 2 下载文件
【发布时间】:2018-05-26 01:48:48
【问题描述】:

我有一个将图像转换为 dataUrl 的代码

  convertToDataURLviaCanvas(url, outputFormat){
return new Promise((resolve, reject) => {
  const img = new Image();
  img.crossOrigin = 'anonymous';
  img.onload = () => {
    let canvas = <HTMLCanvasElement> document.createElement('CANVAS'),
      ctx = canvas.getContext('2d'),
      dataURL;
    canvas.height = img.height;
    canvas.width = img.width;
    ctx.drawImage(img, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    resolve(dataURL);
    canvas = null;
  };
  img.src = url;
});

}

并调用这个函数

  this.convertToDataURLviaCanvas('https://www.google.de/images/srpr/logo11w.png', 'image/jpeg').then(imageData => {
  this.zip.file(image.file_name, imageData, {binary: true})

  this.zip.generateAsync({type: 'blob'}).then(content => {
        saveAs(content, 'images.zip');
      });
})

但是 CORS 存在错误

Failed to load https://www.google.de/images/srpr/logo11w.png: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

我该如何解决它

【问题讨论】:

  • 这意味着 google.de 服务器不允许跨域请求,您在客户端无能为力。如果您想使用 Google 服务,请通过 APIs for Developers
  • 一个 hacky 方法是,对于 chrome 你可以下载 CORS 插件chrome.google.com/webstore/detail/allow-control-allow-origi/…
  • 也许有另一种方法可以将文件下载为存档?
  • 其实我需要从后端下载任意数量的文件作为存档
  • 你是什么后端服务器?在应用服务器中,您需要允许跨域请求

标签: javascript angular typescript cors


【解决方案1】:

您无法从客户端代码下载该文件,因为执行您的代码的浏览器代表远程服务器强制执行无跨域策略。您必须对 Google 服务器应用更改才能从 Google 服务器请求 URL。

你可以做的是让你自己的后端下载文件(使用 curl 或你手头的任何东西),然后在那里转换或循环到你的前端。

例如,您可以有一个用于循环的四行 php 脚本(或后端技术中的等效函数):

<?php
header("Content-type: image/png");
echo(readfile("https://www.google.de/images/srpr/logo11w.png"));
?>

【讨论】:

    猜你喜欢
    • 2018-02-09
    • 2019-05-07
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多