1.将.xlsx文件添加到Vue项目中:
将文件复制到Vue项目的合适目录中,通常是public目录。这确保了文件在构建时被正确地包含在最终的发布版本中。
2.在Vue组件中创建动态下载链接
<template>
<div>
<!-- 创建一个按钮,点击时触发 downloadFile 方法 -->
<button @click="downloadFile">下载文件</button>
</div>
</template>
<script>
// 引入 Axios
import axios from 'axios';
export default {
methods: {
async downloadFile() {
try {
// 使用 Axios 发送 GET 请求获取文件的二进制数据
const response = await axios.get('static/设备IP台账.xlsx', {
responseType: 'arraybuffer',
});
// 创建一个 Blob 对象,将二进制数据转换为文件类型
const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
// 创建一个下载链接
const downloadLink = document.createElement('a');
// 使用 window.URL.createObjectURL() 创建一个包含 Blob 数据的 URL
const url = window.URL.createObjectURL(blob);
// 设置下载链接的属性
downloadLink.href = url;
downloadLink.download = '设备IP台账.xlsx';
// 将下载链接添加到页面中
document.body.appendChild(downloadLink);
// 模拟点击下载链接,触发文件下载
downloadLink.click();
// 清理下载链接和释放 URL 对象
document.body.removeChild(downloadLink);
window.URL.revokeObjectURL(url);
} catch (error) {
// 处理下载文件时可能发生的错误
console.error('下载文件时发生错误:', error);
}
},
},
};
</script>
说明:
'responseType': 这是 Axios 请求配置的一个选项,用于指定响应的数据类型。'arraybuffer': 这是一种二进制数据类型,表示响应数据以数组缓冲区的形式返回。
在这个特定的代码中,通过将 responseType 设置为 'arraybuffer',我们告诉 Axios 服务器响应应该以二进制数组缓冲区的形式返回。这在下载文件时特别有用,因为文件通常是二进制数据,而不是文本数据。