使用node.js实现附件上传的前后端代码,使用muliter中间件实现
时间: 2024-02-19 11:58:13 浏览: 22
以下是使用 Node.js 和 Multer 中间件实现附件上传的前后端代码示例:
后端(Node.js):
```javascript
const express = require('express');
const multer = require('multer');
const app = express();
// Multer Configuration
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/path/to/destination');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
const upload = multer({ storage: storage });
// Route to handle file upload
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).send('No files were uploaded.');
}
res.send('File uploaded!');
});
app.listen(3000, () => console.log('Server started on port 3000'));
```
前端:
```html
<!DOCTYPE html>
<html>
<head>
<title>File Upload Example</title>
</head>
<body>
<h1>File Upload Example</h1>
<form action="http://localhost:3000/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<br><br>
<input type="submit" value="Upload">
</form>
</body>
</html>
```
在上面的代码中,我们使用了 `multer` 中间件来处理文件上传。在后端代码中,我们配置了 Multer 的存储引擎,然后使用 `upload.single()` 方法来处理单个文件上传。在前端代码中,我们使用了标准的 HTML 表单来允许用户选择要上传的文件。