简体   繁体   中英

Download PDF file is not working with angular and JavaScript

在此处输入图片说明

I am using below code for downloading PDF files.File is downloaded but doesn't contain any data.

     var blob = new Blob([response], { type: "text/plain"});
     var url = window.URL.createObjectURL(blob); 
     var link = document.createElement('a');
     link.href = url;
     link.download = e.coAttachmentName; 
     link.click();

Use FileSaver.js , get it from here https://github.com/eligrey/FileSaver.js/

var filename = new Date();
var blob = new Blob([response], {type: "application/pdf;charset=utf-8"});
saveAs(blob, filename +".pdf");

saveAs will download a pdf file for you.

First of all your request response type has to be arraybuffer .

function openFile(response,fileName,saveFile){
  var fileURL;
  var contentType = response.headers('Content-Type');
  var blob = new $window.Blob([response.data], { type: contentType });
  if(saveFile){
      saveAs(blob, fileName);
  }else{
    if($window.navigator.msSaveOrOpenBlob){
        $window.navigator.msSaveOrOpenBlob(blob , fileName);
    }else{
        fileURL = URL.createObjectURL(blob);
        $window.open(fileURL, '_blank');
    }
  }
}

$window is an AngularJS service - reference to browers window object.

$window.navigator.msSaveOrOpenBlob - it's a method specific to IE browser that supports creating and downloading files insted of Blob URL which isn't supported by IE.

saveAs - https://github.com/eligrey/FileSaver.js/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM