Last active
July 19, 2019 10:50
-
-
Save blattmann/a682979463a27e1818bb1f8acd38e5a9 to your computer and use it in GitHub Desktop.
IE11 force download
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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