1. 第一种方法:使用动态创建a标签的方法
function downloadFile(url, fileName) {
2 const link = document.createElement('a');
3 link.href = url;
4 link.download = fileName;
5 document.body.appendChild(link);
6 link.click();
7 document.body.c
8}
9
10// 使用示例
11downloadFile('/path/to/your/file.txt', 'filename.txt');
我一开始使用的就是这个方法,但是不知道为什么下载文件里面是空白的
2.第二中方法:使用fetch来异步下载blob文件对象的方法
async function downloadLocalFile(fileName) {
2 try {
3 // 这里的URL应该是相对于当前模块的URL或者是一个完整的可访问URL
4 const url = new URL(`./path/to/your/${fileName}`, import.meta.url).toString();
5
6 const response = await fetch(url);
7 if (!response.ok) {
8 throw new Error(`Failed to fetch file: ${response.statusText}`);
9 }
10
11 const blob = await response.blob();
12
13 // 创建隐藏的可下载链接
14 const link = document.createElement('a');
15 link.style.display = 'none';
16 document.body.appendChild(link);
17
18 // 设置下载属性和链接
19 link.href = URL.createObjectURL(blob);
20 link.download = fileName; // 文件名应该包含后缀
21
22 // 触发点击
23 link.click();
24
25 // 清理
26 document.body.removeChild(link);
27 URL.revokeObjectURL(link.href);
28 } catch (error) {
29 console.error('Download error:', error);
30 }
31}
32
33// 调用函数下载文件
34 downloadLocalFile('example.txt'); // 替换为你的文件名
为了方便理解我通过ai加上了注释,第一种方法我下载txt文本没有问题,但是我需要下载的文件是一个xls的表格,下载后打开里面空白,可能是地址问题,也不太清楚,换了第二种方法下载成功打开也OK