Created
March 18, 2020 06:16
-
-
Save evangwt/3e0974e415167da3ca65041621bd106b to your computer and use it in GitHub Desktop.
download file by axios with post
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
function download() { | |
let token = ''; | |
let data = {id: id}; | |
new Promise((resolve, reject) => { | |
axios({ | |
url: `/`, | |
method: 'POST', | |
headers: {'X-USER-TOKEN': token}, // custom token | |
data: data, // json object | |
responseType: 'blob', // important! | |
}) | |
.then(res => { | |
// server header should add Content-Disposition to Access-Control-Expose-Headers | |
let filename = res.request.getResponseHeader('Content-Disposition'); | |
filename = filename ? filename.split('filename=')[1] : Date.now(); | |
console.log('filename', filename); | |
resolve({ | |
name: filename, | |
blob: res.data, | |
}); | |
}) | |
}) | |
.then(file => { | |
console.log('file', file); | |
const blobUrl = window.URL.createObjectURL(file.blob); | |
const a = document.createElement('a'); | |
a.download = file.name; | |
a.href = blobUrl; | |
a.click(); | |
}) | |
.catch(err => { | |
console.log(err.response); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment