Last active
July 28, 2016 06:54
-
-
Save nchevobbe/03a3e3a3ae9e3358ca005284c7bd54e2 to your computer and use it in GitHub Desktop.
Download d'un fichier PDF en JS, avec fallback pour les navigateurs ne supportant pas les blobs
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
if (!Ext.isEmpty(window.URL) && Ext.isFunction(window.URL.createObjectURL)) { | |
//Alors on va effectuer une requête ajax | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET', url, true); | |
xhr.responseType = 'blob'; | |
xhr.onload = function(e) { | |
//Et si tout s'est bien passé | |
if (this.status == 200) { | |
//Alors on construit un blob avec la réponse | |
var blob = new Blob([this.response], { | |
type: config.fileType || 'application/pdf' | |
}); | |
//On en génère un URL | |
var url = window.URL.createObjectURL(blob); | |
//Et on va regarder si on a dans les paramètres un nom de fichier | |
var fileName = config.fileName || 'fichier'; | |
if (!Ext.isEmpty(config) && !Ext.isEmpty(config.params) && !Ext.isEmpty(config.params.filename)) { | |
fileName = config.params.filename; | |
} else if (!Ext.isEmpty(config.url)) { | |
var split = config.url.split('?'); | |
if (split.length > 1) { | |
var params = Ext.Object.fromQueryString(split[1]); | |
if (!Ext.isEmpty(params.filename)) { | |
fileName = params.filename; | |
} | |
} | |
} | |
//Et on peut alors resolve notre promise | |
resolve(url); | |
if (navigator.msSaveBlob) { | |
navigator.msSaveBlob(blob, fileName + "." + (config.fileExtension || "pdf")); | |
} else { | |
//On construit alors une balise <a>, avec l'attribut "download" qui permet de spécifier le nom du fichier qui sera téléchargé | |
var a = el.createChild({ | |
tag: 'a', | |
href: url, | |
download: fileName + "." + (config.fileExtension || "pdf") | |
}); | |
//Et on lance le click sur le lien pour afficher le fenêtre de téléchargement | |
a.dom.click(); | |
} | |
} else { | |
//Si il y a eu un problème, on reject avec le code erreur | |
reject({ | |
status: this.status, | |
message : this.statusText | |
}); | |
} | |
}; | |
xhr.send(); | |
} else { | |
resolve(url); | |
window.location = url; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment