【问题标题】:How to download image from URL (using blob) in angular 5如何以角度5从URL(使用blob)下载图像
【发布时间】:2020-09-11 19:58:25
【问题描述】:

我的网络应用程序中的链接很少,其中一些链接有content type application/pdf 和一些image/jpeg 点击下载/保存文件(相应类型)

我在下载图像时遇到问题,但以下代码非常适合应用程序/pdf,

我在从 URL 下载图像方面需要帮助。我尝试将Content type 和响应类型更改为image/jpeg,但它不起作用。

downloadDocFile(fileLocation, fileName) {

var fileNAme = fileName;
var url = fileLocation;

let headerD = this.service.getHeaderDict();

const headerDict = {
  'Content-Type': 'application/pdf',
  'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
  'Access-Control-Allow-Headers': 'Authorization, X-Requested-With, Content-Type, Origin, Accept, X-clientid, X-locale, X-loggedin, X-version',
  'Access-Control-Allow-Credentials': true
}

const requestOptions = {
  headers: new Headers(headerDict), responseType: ResponseContentType.Blob
};

const proxyurl = "https://cors-anywhere.herokuapp.com/";

this.http.get(proxyurl +url,requestOptions).subscribe(
  res => {
    const data: Blob = new Blob([res.blob()], { type: 'application/pdf' });
    saveAs(data, fileNAme);
 })}

service.ts

getHeaderDict(): Object {
     return this.headerDict
}

【问题讨论】:

  • 你能写出图片和pdf文件名的例子吗
  • 你检查过这个link

标签: angular typescript download blob


【解决方案1】:
  downloadDocument(fileName) {
    this.documentService.downloadDocument(fileName).subscribe(resFile => {
      var newBlob = new Blob([resFile]);
      // IE doesn't allow using a blob object directly as link href
      // instead it is necessary to use msSaveOrOpenBlob
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(newBlob);
        return;
      }
      // For other browsers: 
      // Create a link pointing to the ObjectURL containing the blob.
      const data = window.URL.createObjectURL(newBlob);
      var link = document.createElement('a');
      link.href = data;
      link.download = fileName;
      // this is necessary as link.click() does not work on the latest firefox
      link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
    })
  }

【讨论】:

  • 这个解决方案对我不起作用,它正在下载为 jpeg 文件但无法打开(错误:不支持文件格式)
【解决方案2】:

试试这个,

this.http.get(proxyurl +url, {
  responseType: 'blob' as 'json',
  headers: new HttpHeaders().append('Content-Type', 'application/json')
}).subscribe(data => saveAs(data, fileNAme));

【讨论】:

  • 这种方法有问题(字符串不能分配给 responseType)
猜你喜欢
  • 2020-06-13
  • 1970-01-01
  • 2019-05-09
  • 2018-05-05
  • 2019-03-07
  • 2019-01-24
  • 1970-01-01
  • 2019-12-24
  • 2019-04-06
相关资源
最近更新 更多