vue下载文件怎么保存到指定目录
时间: 2023-09-03 10:15:45 浏览: 68
由于Vue是运行在浏览器端的JavaScript框架,因此无法直接访问本地文件系统。如果需要将下载的文件保存到指定目录,需要借助后台服务器的支持。
以下是一个示例,假设后台服务器使用Node.js来实现文件下载和保存:
1. 客户端发送下载请求,后台服务器接收到请求并返回文件流。
```javascript
// 客户端代码
axios({
method: 'get',
url: '/api/download',
responseType: 'blob' // 将响应数据转换为blob对象
}).then(response => {
// 获取文件名
const filename = response.headers['content-disposition'].match(/filename=(.*)/)[1];
// 创建一个a标签,设置href属性为文件流地址,设置download属性为文件名
const link = document.createElement('a');
link.href = window.URL.createObjectURL(new Blob([response.data]));
link.download = filename;
link.click(); // 触发下载
}).catch(error => {
console.error(error);
});
// 后台服务器代码
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
app.get('/api/download', (req, res) => {
const file = path.join(__dirname, 'file.pdf');
// 设置响应头,告诉浏览器下载文件
res.set({
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename=file.pdf`
});
// 读取文件流并返回给客户端
fs.createReadStream(file).pipe(res);
});
app.listen(3000, () => {
console.log(`Server started on http://localhost:3000`);
});
```
2. 客户端接收到响应后,创建一个a标签,并将文件流地址设置为href属性,将文件名设置为download属性,然后触发下载。
```javascript
// 获取文件名
const filename = response.headers['content-disposition'].match(/filename=(.*)/)[1];
// 创建一个a标签,设置href属性为文件流地址,设置download属性为文件名
const link = document.createElement('a');
link.href = window.URL.createObjectURL(new Blob([response.data]));
link.download = filename;
link.click(); // 触发下载
```
3. 如果需要将文件保存到指定目录,可以在后台服务器代码中进行处理。例如,使用Node.js的fs模块将文件流写入到指定目录中。
```javascript
// 后台服务器代码
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
app.get('/api/download', (req, res) => {
const file = path.join(__dirname, 'file.pdf');
// 读取文件流并保存到指定目录中
const writeStream = fs.createWriteStream('/path/to/destination/file.pdf');
fs.createReadStream(file).pipe(writeStream);
// 设置响应头,告诉浏览器下载文件
res.set({
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename=file.pdf`
});
// 返回响应
res.send('File saved to destination folder.');
});
app.listen(3000, () => {
console.log(`Server started on http://localhost:3000`);
});
```
以上代码仅供参考,具体实现应根据实际情况进行调整。