node.js如何实现附件上传,把上传的附件保存到服务器,并把上传的附件显示到页面上,并添加一个查看和删除附件的功能的前后端代码
时间: 2024-02-19 17:58:03 浏览: 21
以下是一个完整的上传附件的例子,包括前端页面和后端代码:
前端页面:
```html
<!-- 上传表单 -->
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
<!-- 附件列表 -->
<table>
<thead>
<tr>
<th>Filename</th>
<th>Size</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<% for (var i = 0; i < files.length; i++) { %>
<tr>
<td><a href="/uploads/<%= files[i].filename %>"><%= files[i].originalname %></a></td>
<td><%= formatBytes(files[i].size) %></td>
<td>
<form action="/delete" method="post">
<input type="hidden" name="filename" value="<%= files[i].filename %>">
<button type="submit">Delete</button>
</form>
</td>
</tr>
<% } %>
</tbody>
</table>
```
后端代码:
```javascript
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const app = express();
// 设置上传路径和文件名
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './uploads/');
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// 创建上传对象
const upload = multer({ storage });
// 处理上传请求
app.post('/upload', upload.single('file'), (req, res) => {
// 获取上传的文件信息
const file = req.file;
console.log(file);
// 读取文件内容
fs.readFile(file.path, (err, data) => {
if (err) throw err;
// 写入文件到服务器
fs.writeFile('./public/uploads/' + file.filename, data, (err) => {
if (err) throw err;
res.redirect('/');
});
});
});
// 处理删除请求
app.post('/delete', (req, res) => {
// 获取要删除的文件名
const filename = req.body.filename;
// 删除文件
fs.unlink('./public/uploads/' + filename, (err) => {
if (err) throw err;
res.redirect('/');
});
});
// 显示附件列表
app.get('/', (req, res) => {
// 读取上传的文件列表
fs.readdir('./public/uploads/', (err, files) => {
if (err) throw err;
// 渲染页面
res.render('index', { files });
});
});
// 启动服务器
app.listen(3000, () => {
console.log('Server started on port 3000');
});
```
在上面的代码中,使用了ejs模板引擎来渲染页面,使用了multer中间件来处理上传请求,上传的文件会被保存到'./uploads/'目录下,并且使用了fs模块来读取和写入文件。上传完成后,会重定向到附件列表页面,并列出所有上传的文件。附件列表页面中,每个附件都有一个查看链接和一个删除按钮,可以通过访问链接来查看附件,或者通过删除按钮来删除附件。