Node.js 服务器 使用 multer 中间件 接收文件
以下是使用Node.js和Express框架,结合multer中间件来接收上传文件的示例代码:
首先,安装必要的包:
npm install express multer --save
然后,创建一个简单的服务器来接收文件:
const express = require('express');
const multer = require('multer');
const app = express();
// 设置multer的存储配置
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/') // 确保这个文件夹已经存在
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
const upload = multer({ storage: storage });
// 接收单文件
app.post('/upload-single', upload.single('myFile'), (req, res) => {
const file = req.file;
if (!file) {
return res.status(400).send('No file uploaded.');
}
res.send('File uploaded successfully.');
});
// 接收多文件
app.post('/upload-multiple', upload.array('myFiles', 12), (req, res) => {
const files = req.files;
if (!files) {
return res.status(400).send('No files uploaded.');
}
res.send('Files uploaded successfully.');
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
在HTML表单中,你可以这样上传文件:
<form action="http://localhost:3000/upload-single" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<input type="submit" value="Upload File">
</form>
或者上传多个文件:
<form action="http://localhost:3000/upload-multiple" method="post" enctype="multipart/form-data">
<input type="file" name="myFiles" multiple>
<input type="submit" value="Upload Files">
</form>
确保你的服务器运行的目录中有uploads
文件夹,以便multer
可以存储上传的文件。
评论已关闭