Node.js使用Multer实现文件上传,需配置storage和upload中间件,通过upload.single('file')处理单文件上传,前端表单设置enctype="multipart/form-data"并匹配name字段,或用axios发送FormData,同时可限制文件大小、类型并启用CORS支持。

Node.js 处理文件上传是后端开发中常见的需求,尤其在用户需要上传头像、文档或图片时。实现这一功能需要前后端协同配合。下面详细介绍如何用 Node.js 实现文件上传,并与前端对接。
Multer 是 Node.js Express 框架中最常用的文件上传中间件,专门用于处理 multipart/form-data 类型的请求(即表单上传文件)。
安装 Multer:
npm install express multer
基本服务端代码示例:
立即学习“前端免费学习笔记(深入)”;
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
<p>// 配置存储
const storage = multer.diskStorage({
destination: './uploads/',
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname)); // 重命名文件避免重复
}
});</p><p>// 初始化上传对象
const upload = multer({ storage });</p><p>// 接收单个文件上传的接口
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).json({ error: '没有文件上传' });
}
res.json({
message: '文件上传成功',
filename: req.file.filename,
path: req.file.path
});
});</p><p>app.listen(3000, () => {
console.log('服务器运行在 <a href="https://www.php.cn/link/8e5687e2d6ab87e5da2f833f3e8986a4">https://www.php.cn/link/8e5687e2d6ab87e5da2f833f3e8986a4</a>');
});
注意:确保项目根目录下有 ./uploads 文件夹,否则会报错。
前端通过普通表单即可向 Node.js 后端提交文件。
<form action="https://www.php.cn/link/8e5687e2d6ab87e5da2f833f3e8986a4/upload" method="POST" enctype="multipart/form-data"> <input type="file" name="file" /> <button type="submit">上传文件</button> </form>
说明:
upload.single('file') 中的字段名一致。现代项目多采用前后端分离架构,前端可通过 JavaScript 发送 FormData 请求。
前端代码示例(使用 axios):
const formData = new FormData();
formData.append('file', document.getElementById('fileInput').files[0]);
<p>axios.post('<a href="https://www.php.cn/link/8e5687e2d6ab87e5da2f833f3e8986a4/upload">https://www.php.cn/link/8e5687e2d6ab87e5da2f833f3e8986a4/upload</a>', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(res => {
alert('上传成功:' + res.data.filename);
})
.catch(err => {
alert('上传失败');
});
HTML 部分:
<input type="file" id="fileInput" /> <button onclick="uploadFile()">上传</button>
JavaScript 注意事项:
Content-Type 为 multipart/form-data,让浏览器自动设置(axios 会自动处理)。启用 CORS(如需跨域):
const cors = require('cors');
app.use(cors());为安全考虑,应限制上传文件的类型和大小。
const upload = multer({
storage,
limits: { fileSize: 5 * 1024 * 1024 }, // 限制 5MB
fileFilter: (req, file, cb) => {
const allowedTypes = /jpeg|jpg|png|gif|pdf/;
const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = allowedTypes.test(file.mimetype);
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (extname && mimetype) {
return cb(null, true);
} else {
cb(new Error('不支持的文件类型'));
}} });
错误处理:
app.post('/upload', (req, res, next) => {
upload.single('file')(req, res, function (err) {
if (err) {
return res.status(400).json({ error: err.message });
}
res.json({ message: '上传成功', filename: req.file.filename });
});
});
基本上就这些。Node.js 结合 Multer 可快速实现稳定文件上传,前端只需正确构造表单或发送 FormData 请求即可完成对接。关键点在于字段名匹配、编码类型设置和路径配置。不复杂但容易忽略细节。
以上就是Node.js怎么处理文件上传_Node.js实现文件上传功能与前端对接教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号