我正在开发一个带有 Laravel 后端 API 的 Vue 应用程序。单击链接后,我想调用服务器来下载某个文件(大多数情况下是 PDF 文件)。当我做一个get
请求与axios
我在回复正文中收到了一份 PDF 作为回报。我想直接下载该文件。
为了让您更好地了解响应的情况:
(note: I know a real text response is better than an image but I don't see any way to return that because of the length of the actual PDF content..)
有什么方法可以用 JavaScript 之类的东西下载该文件吗?它必须是直接下载,而无需再次单击按钮。
Code
// This method gets called when clicking on a link
downloadFile(id) {
const specificationId = this.$route.params.specificationId;
axios
.get(`${this.$API_URL}/api/v1/suppliersmanagement/product-specifications/${specificationId}/fileupload/${id}/download`, {
headers: this.headers,
})
.then(response => {
console.log(response);
// Direct download the file here..
})
.catch(error => console.log(error));
},
正如 @Sandip Nirmal 建议我用过的downloadjs
效果非常好!不得不对我的代码进行一些调整,但最终成功了。
我的新代码
// npm i downloadjs
import download from 'downloadjs'
// method
downloadFile(file) {
const specificationId = this.$route.params.specificationId;
axios
.get(`${this.$API_URL}/api/v1/suppliersmanagement/product-specifications/${specificationId}/fileupload/${file.id}/download`, {
headers: this.headers,
responseType: 'blob', // had to add this one here
})
.then(response => {
const content = response.headers['content-type'];
download(response.data, file.file_name, content)
})
.catch(error => console.log(error));
},
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)