Skip to content

Instantly share code, notes, and snippets.

@evangwt
Created March 18, 2020 06:16
Show Gist options
  • Save evangwt/3e0974e415167da3ca65041621bd106b to your computer and use it in GitHub Desktop.
Save evangwt/3e0974e415167da3ca65041621bd106b to your computer and use it in GitHub Desktop.
download file by axios with post
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