Last active
June 29, 2020 12:19
-
-
Save Sidd27/1814e2105d36aaa7004677a86a02fbaa 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
let getFileName = function (header) { | |
let contentDispostion = header.split(';'); | |
const fileNameToken = `filename*=UTF-8''`; | |
let fileName = 'downloaded.pdf'; | |
for (let thisValue of contentDispostion) { | |
if (thisValue.trim().indexOf(fileNameToken) === 0) { | |
fileName = decodeURIComponent(thisValue.trim().replace(fileNameToken, '')); | |
break; | |
} | |
} | |
return fileName; | |
}; | |
let data = { | |
id: 0, | |
name: 'foo' | |
}; | |
let headers = new Headers(); | |
headers.append('Content-Type', 'application/json'); | |
fetch('PDF_API', { | |
method: 'POST', | |
headers: headers, | |
body: JSON.stringify(data) | |
}) | |
.then(async res => ({ | |
filename: getFileName(res.headers.get('content-disposition')), | |
blob: await res.blob() | |
})) | |
.then(resObj => { | |
// It is necessary to create a new blob object with mime-type explicitly set for all browsers except Chrome, but it works for Chrome too. | |
const newBlob = new Blob([resObj.blob], { type: 'application/pdf' }); | |
// MS Edge and IE don't allow using a blob object directly as link href, instead it is necessary to use msSaveOrOpenBlob | |
if (window.navigator && window.navigator.msSaveOrOpenBlob) { | |
window.navigator.msSaveOrOpenBlob(newBlob); | |
} else { | |
// For other browsers: create a link pointing to the ObjectURL containing the blob. | |
const objUrl = window.URL.createObjectURL(newBlob); | |
const link = document.createElement('a'); | |
link.href = objUrl; | |
link.style.display= 'none'; | |
link.download = resObj.filename; | |
link.click(); | |
// For Firefox it is necessary to delay revoking the ObjectURL. | |
setTimeout(() => { window.URL.revokeObjectURL(objUrl); }, 250); | |
} | |
}) | |
.catch((error) => { | |
console.log('DOWNLOAD ERROR', error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment