Created
April 27, 2018 13:24
-
-
Save max2320/dbbeffb33c6f6e505328eb92e0409de8 to your computer and use it in GitHub Desktop.
This file contains 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
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