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

前端向Node.js服务器传图片返回undefined问题求助

解决Multer处理FormData上传图片时后端获取undefined的问题

后端代码修复

  1. 修正文件获取变量名
    你使用了upload.single('file')处理单文件上传,对应获取文件的变量是request.file(单数),而非request.files(复数用于多文件场景);同时文件不会出现在request.body中,直接打印request.file即可。修改接口代码:
app.post('/newTweet',upload.single('file'),(request, response) => {
    console.log(request.file); // 改为单数file
    response.json({ file: request.file });
})
  1. 可选:启用磁盘存储(如需保存文件)
    如果需要将文件保存到服务器本地,取消注释你写的storage配置,替换空的multer实例:
const storage = multer.diskStorage({
    destination: function(req, file, cb){
        return cb(null, './Images');
    },
    filename: function(req, file, cb){
        return cb(null, `${file.originalname}`);
    }
})

const upload = multer({storage});

注意提前创建./Images目录,避免报错。

前端代码修复

  1. 直接发送FormData,避免包装成对象
    你当前把FormData封装到了newPost.file字段中,发送的是JSON对象而非FormData本身,后端无法解析。调整代码如下:
const [imageLoad, setImageLoad] = useState<FormData | undefined>()

const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    
    // 如需附加其他字段,直接加到FormData里
    // 示例:imageLoad?.append('tweetContent', tweetInput.value)
    
    if (imageLoad) {
        apiPost(imageLoad); // 直接传递FormData
    }
}

同时移除newPost相关状态和对应的useEffect,无需再包装数据。

  1. 移除手动设置的content-type
    Axios检测到请求数据为FormData时,会自动生成包含boundary参数的正确multipart/form-data请求头,手动设置会丢失关键参数导致解析失败。修改Axios请求:
// 无需手动设置headers
axios.post('http://localhost:8000/newTweet', data);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 08:10:18