Skip to content

Instantly share code, notes, and snippets.

@blattmann
Last active July 19, 2019 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blattmann/a682979463a27e1818bb1f8acd38e5a9 to your computer and use it in GitHub Desktop.
Save blattmann/a682979463a27e1818bb1f8acd38e5a9 to your computer and use it in GitHub Desktop.
IE11 force download
// Vue.js method to force a file download, in this example a *.jpg
forceDownload(url, fileName) {
const dlFile = fileName || url.substring(url.lastIndexOf('/') + 1);
const mimeType = 'image/jpeg';
const extension = '.jpg';
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
this.trackEvent(url);
xhr.onload = function () {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
// crap browsers! --> IE11
if (this.status === 200) {
const myBlob = this.response;
const newBlob = new Blob([myBlob], {
type: mimeType,
}, {
name: dlFile,
});
window.navigator.msSaveOrOpenBlob(
newBlob,
dlFile,
extension,
);
}
} else {
// good browser
const urlCreator = window.URL || window.webkitURL;
const imageUrl = urlCreator.createObjectURL(this.response);
const tag = document.createElement('a');
tag.href = imageUrl;
tag.download = dlFile;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
};
xhr.send();
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment