Skip to content

Instantly share code, notes, and snippets.

@nchevobbe
Last active July 28, 2016 06:54
Show Gist options
  • Save nchevobbe/03a3e3a3ae9e3358ca005284c7bd54e2 to your computer and use it in GitHub Desktop.
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
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