如何以角度5从URL下载图像(使用Blob)

问题描述 投票:0回答:2

我的Web应用程序中的链接很少,其中一些链接具有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
}
angular typescript download blob
2个回答
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 }));
    })
  }

0
投票

尝试一下,

this.http.get(proxyurl +url, {
  responseType: 'blob' as 'json',
  headers: new HttpHeaders().append('Content-Type', 'application/json')
}).subscribe(data => saveAs(data, fileNAme));
© www.soinside.com 2019 - 2024. All rights reserved.