How can i resolve the error “access is denied” in IE browsers when downloading a PDF from my angular7 application?

安稳与你 提交于 2021-01-29 10:02:53

问题


In my angular 7 application I have an API, when called, will download a PDF.

Here is my methods for getting the PDF:

getPdf() {
  const payload = { applicantId: this.idHeader, codes: 
  this.codeHeader + ':0', genderType: this.gender, data: this.data }

  this.service.getPdfConfirmationView(payload).subscribe((pdfResponse: 
  any) => {
    let dataType = 'application/pdf';
    let binaryData = [];
    binaryData.push(pdfResponse);
    let downloadLink = document.createElement('a');
    downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, { type: dataType }));
    if (pdfResponse)
      downloadLink.setAttribute('download', 'ConfirmationReport');
    document.body.appendChild(downloadLink);
    downloadLink.click();
    })
  }

Here is my service for connecting to the API

  getPdfConfirmationView(payload) {
    return this.http.get(environment.apiUrl + 
    '/v1/report/getPdfConfirmationView',
    { headers: this.getSearchApiHeaders(payload), responseType: 'blob' });
  }

This works fine in Chrome browsers, I'm able to click on the link and download a PDF file to my computer. However, in Internet Explorer 11, I am getting this error message:

ERROR Error: Access is denied.
  "ERROR"
    [object Error]{description: "Access is d...", message: "Access is d...", name: "Error", number: -2147024891, stack: "Error: Acce..."}
    [functions]
    __proto__[object Error] {...}
    description"Access is denied. ...
    message"Access is denied. ...
    name"Error"
    number-2147024891
    stack"Error: Access is denied. ...

What can I do to resolve this in IE browsers?


回答1:


IE doesn't support URL.createObjectURL() which you use in your methods for getting PDFs. IE has its own API for creating and downloading files, which is called msSaveBlob or msSaveOrOpenBlob.

The difference between the msSaveBlob and msSaveOrOpenBlob methods is that the former only provides a Save button to the user whereas the latter provides both a Save and an Open button. You could use them like this in IE:

window.navigator.msSaveOrOpenBlob(blobData, fileName);  

For more information, you could refer to this article in Microsoft and this thread.

---------------------------------------------------Edit-------------------------------------------------------

To make it cross browser, the code is like below:

if(window.navigator.msSaveOrOpenBlob) {
    //IE11 & Edge
    window.navigator.msSaveOrOpenBlob(blobData, fileName); 
}
else{
   //Other browsers
    window.URL.createObjectURL(blobData);
    ...
}

You could also refer to this simple sample I made: https://stackblitz.com/edit/angular-coueov



来源:https://stackoverflow.com/questions/58175099/how-can-i-resolve-the-error-access-is-denied-in-ie-browsers-when-downloading-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!