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

浏览器上传图片至Node.js服务器失败,req.files返回undefined求助

解决Node.js服务器req.files为undefined的文件上传问题

问题场景

尝试从浏览器上传图片到Node.js服务器,打印req.files结果为undefined,无法完成文件上传。前端使用FormData通过fetch发送请求,后端处理逻辑依赖req.files获取文件。

前端代码

const uploadFile = (file) => {
  // add the file to the FormData object
  const fd = new FormData();
  fd.append("avatar", file);

  // send `POST` request
  fetch("http://localhost:3001/uploadtoazure", {
    method: "POST",
    body: fd,
  })
    .then((res) => res.json())
    .then((json) => console.log(json))
    .catch((err) => console.error(err));
};

// select file input
const input = document.getElementById("upload");

// add event listener
input.addEventListener("change", () => {
  uploadFile(input.files[0]);
});

后端路由处理代码

async function uploadToAzure(req, res, next) {

  try {
    console.log(req.files);
    if (!req.files) {
      res.send({
        status: false,
        message: 'No file uploaded'
      })
    } else {
      // Use the name of the input field (i.e. "avatar") to retrieve the uploaded file
      let avatar = req.files.avatar

      // Use the mv() method to place the file in the upload directory (i.e. "uploads")
      avatar.mv('./uploads/' + avatar.name)

      //send response
      res.send({
        status: true,
        message: 'File is uploaded',
        data: {
          name: avatar.name,
          mimetype: avatar.mimetype,
          size: avatar.size
        }
      })
    }
  } catch (err) {
    res.status(500).send(err)
  }
}

核心原因

Express默认不处理multipart/form-data格式的请求,你后端代码中使用的req.files依赖第三方中间件解析这类请求,未配置对应中间件会导致无法获取上传的文件。

解决步骤

1. 安装express-fileupload中间件

你的后端代码用到了req.files.avatar.mv()方法,这是express-fileupload库提供的API,先安装这个包:

npm install express-fileupload

2. 在Express应用中注册中间件

在Express主文件(如app.js或server.js)中,在路由之前添加中间件注册代码:

const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();

// 注册文件上传中间件
app.use(fileUpload());

// 挂载你的路由
app.post('/uploadtoazure', uploadToAzure);

app.listen(3001, () => console.log('Server running on port 3001'));

3. 排查其他潜在问题

  • CORS拦截:若前端和服务器端口不同,需配置CORS中间件:
    npm install cors
    
    注册代码:
    const cors = require('cors');
    app.use(cors());
    
  • 上传目录存在性:确保./uploads目录已创建,否则mv()方法会报错,可通过命令创建:
    mkdir uploads
    
  • 请求路径匹配:确认前端请求的/uploadtoazure和后端路由路径完全一致,注意大小写和斜杠。

验证

重启服务器后重新上传文件,此时req.files应能正确获取到上传的文件对象,文件会被保存到uploads目录中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:34:57