Skip to content

Instantly share code, notes, and snippets.

@max2320
Created April 27, 2018 13:24
Show Gist options
  • Save max2320/dbbeffb33c6f6e505328eb92e0409de8 to your computer and use it in GitHub Desktop.
Save max2320/dbbeffb33c6f6e505328eb92e0409de8 to your computer and use it in GitHub Desktop.
import Promise from 'promise-polyfill';
import fetchPonyfill from 'fetch-ponyfill';
if (!window.Promise) {
window.Promise = Promise;
}
const {fetch, Request, Response, Headers} = fetchPonyfill();
export default class Download {
constructor(url, name){
this.url = url;
this.name = name;
}
buildheader(headers){
return window.session.applySessionHeader(headers);
}
buildRequest(){
var params = {
method: "GET",
headers: this.buildheader({})
};
return new Request(this.url, params);
}
getExtension(){
if(this.url.indexOf('export') != -1 || this.url.indexOf('print') != -1){
if(this.url.indexOf('export') != -1){
extension = '.xls'
}else{
extension = '.pdf'
}
}else{
var extension = "." + this.url.split('.').pop();
}
return extension;
}
download(){
fetch(this.buildRequest())
.then(response => response.blob())
.then((blob) => {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
}else{
var url = URL.createObjectURL(blob)
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.download = this.name + this.getExtension();
a.click();
URL.revokeObjectURL(url);
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment