使用SweetAlert2+Express.js上传图片时服务端req.file为undefined
问题说明
- 实现目标:基于SweetAlert2 + Express.js 完成图片上传到服务端的功能
- 异常表现:使用原生带
name属性的HTML文件选择控件时上传正常,替换为SweetAlert2内置文件输入组件后功能失效 - 排查现状:前端通过
console.log(result)可以正常拿到选中的图片对象,但服务端执行console.log(req.file)始终输出undefined;请求发送使用原生Fetch API,未引入Ajax、jQuery类第三方请求库
原有问题代码
客户端代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> </body> <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script> </html>
async function start() { await Swal.fire({ title: "Please Select Image File", input: "file", inputAttributes: { accept: "image/*", "aria-label": "Select Image", }, showLoaderOnConfirm: true, preConfirm: (result) => { console.log(result); const reader = new FileReader(); console.log(file); // 此处file未定义,会直接抛错 reader.onload = (e) => { let timerInterval; Swal.fire({ title: "Wait for Upload", imageUrl: e.target.result, iamgeHeight: 200, // 属性拼写错误 imageWidth: 200, imageAlt: "The uploaded picture", didOpen: () => { Swal.showLoading(); return fetch(`${MY_SERVER_URL}`, { method: "POST", headers: { Accept: "application/json", }, body: reader, // 错误传入FileReader实例,不符合表单上传格式要求 }) .then((response) => { if (!response.ok) { throw new Error(response.statusText); } return response.json(); }) .catch((error) => { Swal.showValidationMessage( `Request failed: ${error}` ); }); }, willClose: () => { console.log('Nothing') }, }).then((result) => { if (result.dismiss === Swal.DismissReason.timer) { console.log("I was closed by the timer"); } }); }; reader.readAsDataURL(result); }, }); } start();
服务端代码(Express.js)
var express = require("express"); var router = express.Router(); const multer = require("multer"); var storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, "./public/images"); }, filename: (req, file, cb) => { console.log(file); var filetype = ""; if (file.mimetype === "image/gif") { filetype = "gif"; } if (file.mimetype === "image/png") { filetype = "png"; } if (file.mimetype === "image/jpeg") { filetype = "jpg"; } cb(null, "image-" + Date.now() + "." + filetype); }, }); var upload = multer({ storage: storage, }); router.post("/uploadImage", upload.single("file"), async (req, res, next) => { console.log(req.file); console.log("good"); let fileName = req.file.filename; res.redirect( `${MY_SERVER_URL_REDIRECT_URL}` ); });
故障原因
- 请求格式错误:Multer仅解析
multipart/form-data格式的请求体,原代码直接把FileReader实例作为Fetch的body传入,既不是标准表单格式,也没有匹配后端upload.single("file")要求的file字段名 - 请求头设置错误:发送
multipart/form-data请求时禁止手动设置Content-Type头,浏览器会自动生成带boundary分隔符的请求头,手动设置会导致分隔符丢失,Multer无法解析文件内容 - 逻辑结构错误:上传请求逻辑嵌套在第二个弹窗的
didOpen生命周期中,preConfirm钩子没有正确返回Promise,SweetAlert2自带的加载、错误提示逻辑完全失效 - 语法错误:存在未定义变量引用、属性拼写错误(
iamgeHeight应为imageHeight),会直接阻断代码执行 - 多余逻辑:不需要用
FileReader把文件转成base64格式,直接上传原始File对象即可,转码操作反而会增加请求体积、浪费性能
修复方案
修复后客户端代码
async function start() { const { value: file, isConfirmed } = await Swal.fire({ title: "请选择图片文件", input: "file", inputAttributes: { accept: "image/*", "aria-label": "选择图片", }, showLoaderOnConfirm: true, // preConfirm必须返回Promise,供SweetAlert2处理加载/错误状态 preConfirm: (file) => { if (!file) return false; // 构建标准FormData对象,字段名必须和后端multer.single()的参数一致 const formData = new FormData(); formData.append("file", file); // 发请求,不要手动设置Content-Type return fetch("/uploadImage", { method: "POST", body: formData }) .then(async (response) => { if (!response.ok) { throw new Error(await response.text() || "上传失败"); } return response.json(); }) .catch((error) => { Swal.showValidationMessage(`请求失败: ${error.message}`); }); }, }); // 上传成功后弹出预览弹窗 if (isConfirmed && file) { const reader = new FileReader(); reader.onload = (e) => { Swal.fire({ title: "上传成功", imageUrl: e.target.result, imageHeight: 200, imageWidth: 200, imageAlt: "上传的图片", }); }; reader.readAsDataURL(file); } } start();
服务端注意事项
原有服务端代码逻辑基本可用,仅需确认三点:
- 路由正确挂载到Express实例,上传接口路径和前端请求路径一致
./public/images目录存在且有写入权限,避免文件写入失败- 如果前端需要接收JSON响应,把接口里的
res.redirect逻辑改为返回JSON格式即可,示例:res.json({ success: true, filename: fileName })
内容的提问来源于stack exchange,提问作者writingdeveloper
相关产品推荐
相关产品推荐

