前端如何实现点击下载弹出功能页面选择下载路径以及更改文件名,并获取路径、文件名
时间: 2024-01-17 18:05:14 浏览: 41
实现点击下载弹出功能页面选择下载路径以及更改文件名,并获取路径、文件名,可以通过以下步骤实现:
1. 在 HTML 页面中添加一个下载按钮,通过 JavaScript 绑定按钮的点击事件。
```html
<button id="download-btn">下载文件</button>
```
2. 在 JavaScript 中获取下载按钮,并为其绑定点击事件。在点击事件中创建一个隐藏的表单,设置表单的 action 属性为文件的下载地址,然后提交表单。
```javascript
const downloadBtn = document.querySelector('#download-btn');
downloadBtn.addEventListener('click', function() {
const form = document.createElement('form');
form.setAttribute('action', '/download/file');
form.setAttribute('method', 'GET');
form.style.display = 'none';
// 创建文件名输入框
const filenameInput = document.createElement('input');
filenameInput.setAttribute('type', 'text');
filenameInput.setAttribute('name', 'filename');
filenameInput.setAttribute('value', 'default.txt');
form.appendChild(filenameInput);
// 创建保存路径输入框
const filepathInput = document.createElement('input');
filepathInput.setAttribute('type', 'text');
filepathInput.setAttribute('name', 'filepath');
filepathInput.setAttribute('value', '/home/user/downloads');
form.appendChild(filepathInput);
document.body.appendChild(form);
form.submit();
});
```
3. 在服务器端接收表单提交的数据,并根据数据生成文件并返回给客户端。在 Node.js 中,可以使用 `fs` 模块来生成文件。
```javascript
const fs = require('fs');
const path = require('path');
app.get('/download/file', function(req, res) {
const filename = req.query.filename || 'default.txt';
const filepath = req.query.filepath || '/home/user/downloads';
const fileContent = 'This is the content of the file.';
const filePathname = path.join(filepath, filename);
fs.writeFile(filePathname, fileContent, function(err) {
if (err) {
console.error(err);
return res.status(500).end();
}
res.download(filePathname, filename, function(err) {
if (err) {
console.error(err);
return res.status(500).end();
}
fs.unlink(filePathname, function(err) {
if (err) {
console.error(err);
}
});
});
});
});
```
这样,用户就可以通过点击下载按钮,弹出功能页面选择下载路径以及更改文件名,并获取路径、文件名。服务器端会生成相应的文件,并将其发送给客户端进行下载。