Vue项目中如何实现下载功能?
1.给一个按钮绑定点击事件:
<li v-for="item in componentData.image_path">
<div>
<span>{{ item.name }}</span>
<el-button type="text" @click="downloadFile(item.path, item.name)">
下载
</el-button>
</div>
</li>
2.定义方法
downloadFile(fileUrl, fileName) {
var baseUrl = 'http://192.168.0.70'
const xhr = new window.XMLHttpRequest();
xhr.open("GET", baseUrl + "/download?url=" + fileUrl, true);
xhr.responseType = "blob";
xhr.onload = () => {
const url = window.URL.createObjectURL(xhr.response);
const link = document.createElement("a");
link.href = url;
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
link.remove();
};
xhr.send();
},