Axios js是非常流行的HTTP请求。你可以在Vue js, node js, react js中使用Axios js来启动get, post, put等请求,但如果你需要同样的要求来从API下载文件响应,并使用Axios js来进行下载,那么你如何做到这一点?我会帮你用Axios做文件下载。
Axios HTTP Code
axios({
url: 'http://localhost:8000/api/get-file',
method: 'GET',
responseType: 'blob',
}).then((response) => {
var fileURL = window.URL.createObjectURL(new Blob([response.data]));
var fileLink = document.createElement('a');
fileLink.href = fileURL;
fileLink.setAttribute('download', 'file.pdf');
document.body.appendChild(fileLink);
fileLink.click();
});
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Download File using Axios Vue JS? - HackTheStuff</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js" integrity="sha256-S1J4GVHHDMiirir9qsXWc8ZWw74PHHafpsHp5PXtjTs=" crossorigin="anonymous"></script>
</head>
<body>
<div id="app">
<button @click="onClick()">DownLoad</button>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
methods: {
onClick() {
axios({
url: 'http://localhost:8000/my.pdf',
method: 'GET',
responseType: 'blob',
}).then((response) => {
var fileURL = window.URL.createObjectURL(new Blob([response.data]));
var fileLink = document.createElement('a');
fileLink.href = fileURL;
fileLink.setAttribute('download', 'file.pdf');
document.body.appendChild(fileLink);
fileLink.click();
});
}
}
})
</script>
</body>
</html>
欢迎访问:https://blog.blessedbin.com/2021/12/19/%E5%88%A9%E7%94%A8Axios%E4%B8%8B%E8%BD%BD%E6%96%87%E4%BB%B6/