You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js路由异常:Summernote图片上传出现Internal Server Error

问题排查与解决

核心问题:字段名不匹配

前端sendFile函数中,FormData添加的文件字段名为"file":

data.append("file", file);

但后端路由里Multer的upload.array指定的字段名是动态生成的"note-dialog-image-file-16755274670761",两者不匹配导致Multer无法解析文件,进而触发服务器内部错误。

修复步骤

1. 修正后端路由的字段名

根据前端实际传递的字段名,将Multer的字段参数改为"file"。结合前端循环单文件上传的逻辑,推荐使用upload.single更贴合场景:

router.post("/img", upload.single("file"), (req, res) => {
    console.log("파일 이름 : ", req.file);
    const url = `/img/${req.file.filename}`;
    res.json(url); // 直接返回单个图片URL,适配前端单文件上传逻辑
});

如果想支持批量上传,可修改前端一次性传递所有文件:

onImageUpload : function(files, editor, welEditable){
    sendFiles(files, editor, welEditable);
}

function sendFiles(files, editor, welEditable){
    const data = new FormData();
    files.forEach(file => data.append("file", file));
    $.ajax({
        data: data,
        type: "POST",
        url: "/post/img",
        cache: false,
        contentType: false,
        processData: false,
        success: function(urls) {
            urls.forEach(url => editor.insertImage(welEditable, url));
        }
    });
}

对应的后端路由调整为:

router.post("/img", upload.array("file", 4), (req, res) => {
    console.log("파일 이름 : ", req.files);
    const urlArr = req.files.map(file => `/img/${file.filename}`);
    res.json(urlArr); // res.json会自动处理数组序列化,无需手动JSON.stringify
});

2. 检查Multer基础配置

确保已正确初始化Multer的存储路径,且目标目录存在:

const multer = require('multer');
const path = require('path');

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const uploadDir = path.join(__dirname, '../public/img');
        // 可添加目录存在性检查,避免报错
        cb(null, uploadDir);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, `${file.fieldname}-${uniqueSuffix}${path.extname(file.originalname)}`);
    }
});

const upload = multer({ storage: storage });

3. 配置静态资源访问

确保Express已配置/img目录的静态资源访问,否则前端无法加载上传后的图片:

app.use('/img', express.static(path.join(__dirname, 'public/img')));

4. 权限检查

确认服务器端的文件上传目录具备Node.js进程的读写权限,避免因权限不足导致上传失败。

内容的提问来源于stack exchange,提问作者quail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 16:01:18