简体   繁体   中英

JavaScript: Save file via data URL in IE

I have an app that converts files. I'm sending a file, and the converted file is being returned in the form of a data URL. Had everything working great in Chrome, but IE (10/11/Edge) is a different story. Have tried several things to no prevail:

1) HTML5 download attribute is not supported in IE. I tried assigning the returned URL as an anchor tag href, but invoking .click() is not supported, and manually clicking on the link does nothing.

2) window.navigator.msSaveOrOpenBlob() and File Saver.js . The SaveAs dialog pops up, but the blob is empty and never downloads anything.

var file= new Blob([returnedFile], {type: "application/pdf"});
window.navigator.msSaveOrOpenBlob(file, 'doc.pdf');
FileSaver.saveAs(file, 'doc.pdf');

Any ideas or suggestions to try?

First, try to verify saveAs existance:

if (window.saveAs) { 
    window.saveAs(blob, name); 
} else { 
    navigator.saveBlob(blob, name); 
}

As for the Blob itself:

  • create <a>
  • update href :

    a.href = window.URL.createObjectURL(new Blob(returnedFile, {type: "application/pdf"}));

  • fire click event

More or less the same functionality can be reviewed there: http://jsfiddle.net/VB59f/2/

Ended up getting the browser via navigator.userAgent.match and handling the save based on each browser accordingly:

 var saveData = (data, fileName) => {

IE:

FileSaver.saveAs(blob, fileName + "." + extension);

Chrome:

var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
downloadLink.style.display = "none";
downloadLink.href = data;
downloadLink.download = fileName;
downloadLink.click();

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