Created
July 2, 2019 07:54
-
-
Save enqtran/3af740541e0dcbfdffeed99c15912de3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 axios from "axios"; | |
const open_download_file = async (url, file_name) => { | |
return await axios({ | |
url: url, | |
method: 'GET', | |
responseType: 'blob', // important | |
onDownloadProgress: (progressEvent) => { | |
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); | |
console.log(`download ${percentCompleted}%`); | |
} | |
}) | |
.then((response) => { | |
if (response.status === 200 && response.statusText === "OK") { | |
const url_file = window.URL.createObjectURL(new Blob([response.data])); | |
const link = document.createElement('a'); | |
link.href = url_file; | |
link.setAttribute('download', file_name); | |
window.document.body.appendChild(link); | |
link.click(); | |
window.URL.revokeObjectURL(url); | |
window.document.body.removeChild(link); | |
return true; | |
} else { | |
return false; | |
} | |
}) | |
.catch(err => { | |
if (err.response.status === 404) { | |
console.log(err.response.status); | |
} else { | |
console.log(err.response.status); | |
} | |
return false; | |
}); | |
} | |
export default open_download_file; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment