Express服务器无法接收PDF上传文件,报边界相关错误求助
问题解决:React PDF上传至Express服务器失败的修复方案
React组件端修复
问题根源在于手动指定了Content-Type的boundary,FormData对象会自动生成并设置正确的请求头(包含匹配的boundary),手动设置会导致与FormData内部生成的边界不匹配,引发解析错误。
修改handleUpload函数,移除手动设置的Content-Type头:
const handleUpload = async () => { const formData = new FormData(); formData.append('file', file); formData.append('name', file.name); try { const response = await fetch('http://localhost:3001/upload', { method: 'POST', body: formData // 移除手动设置的Content-Type,浏览器会自动处理请求头 }); const result = await response.text(); alert(result); } catch (error) { console.error(error); alert('Failed to upload the file.'); } };
Express服务器端修复
- 错误地将
upload.single('file')作为全局中间件使用,会导致所有请求都被multer解析,非文件上传请求会出现异常,应仅在/upload路由上应用该中间件。 - 多余的
bodyParser和express.urlencoded/json中间件会与multer冲突,multer专门处理multipart/form-data类型请求,bodyParser无法处理这类请求,需移除不必要的解析中间件。
修改后的服务器代码:
const express = require('express'); const multer = require('multer'); const path = require('path'); const app = express(); const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'C:\\Users\\Propietario\\OneDrive\\Documentos\\pdf-files'); }, filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); } }); const fileFilter = (req, file, cb) => { if (file.mimetype === 'application/pdf') { cb(null, true); } else { cb(null, false); } }; const upload = multer({ storage: storage, fileFilter: fileFilter }); // 仅在/upload路由应用文件上传中间件 app.post('/upload', upload.single('file'), (req, res) => { console.log(req.body); // 可获取name字段内容 if (!req.file) { return res.status(400).send('No file was uploaded or the file type is not supported.'); } const fileName = req.file.originalname; res.send(`File ${fileName} was uploaded and stored as ${req.file.filename}.`); }); const port = process.env.PORT || 3001; app.listen(port, () => { console.log(`Server listening at http://localhost:${port}`); });
关键注意点
- React端:永远不要手动为FormData设置
multipart/form-data类型的Content-Type,浏览器会自动生成包含正确boundary的请求头。 - Express端:multer中间件应仅在需要处理文件上传的路由上使用,避免全局应用引发冲突;处理multipart请求时无需使用bodyParser,multer已替代其对应功能。
内容的提问来源于stack exchange,提问作者A B
相关产品推荐
相关产品推荐

