我正在尝试使用 React Hook Form 上传文件并将它们发送到我的后端,我在后端使用 multer 和 Cloudinary 来处理文件上传。当我使用 Postman 测试 API 时,
req.files
已正确填充。但是,当我从 React 前端提交表单时,req.files
未定义。请帮忙!
NewStampForm.jsx
export default function NewStampForm() {
const auth = useAuthUser();
const authHeader = useAuthHeader();
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
const onSubmit = async (formData) => {
console.log(formData);
try {
const res = await axios.post(
`${import.meta.env.VITE_BACKEND_URL}/stamps`,
formData,
{
headers: {
Authorization: authHeader,
},
}
);
} catch (e) {
console.log(e);
}
};
return (
<div>
<div className="text-xl">New Stamp</div>
<form onSubmit={handleSubmit(onSubmit)} encType="mu">
<input
{...register("title", { required: true })}
placeholder="Stamp title"
/>
{errors.title && <span>This field is required</span>}
<input {...register("price", { required: true })} type="number" />
{errors.price && <span>This field is required</span>}
<input
{...register("img", { required: true })}
type="file"
name="img"
multiple
/>
{errors.img && <span>This field is required</span>}
<input type="submit" />
</form>
</div>
);
}
控制器
const createNewStamp = async (req, res) => {
try {
const { title, price, img } = req.body;
console.log(req.files);
const newStamp = await Stamp.create({ title, price });
res.status(200).json(newStamp);
} catch (e) {
errorResponse(res, e);
}
};
云的东西
require("dotenv").config();
const cloudinary = require("cloudinary").v2;
const { CloudinaryStorage } = require("@fluidjs/multer-cloudinary");
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_KEY,
api_secret: process.env.CLOUDINARY_SECRET,
});
const storage = new CloudinaryStorage({
cloudinary: cloudinary,
params: {
folder: "Mudrank", // Optional: Folder for uploaded files in Cloudinary
allowed_formats: ["jpg", "jpeg", "png"], // Optional: Restrict allowed file types
},
});
module.exports = {
cloudinary,
storage,
};
邮票路线
router
.route("/")
.get(verifyCircle, getAllStamps)
.post(verifyCircle, upload.array("img"), createNewStamp);
当我通过 React hook 表单发送它时,req.files
只是未定义。但是,当我使用邮递员发送req.body
时,它就被定义了。
img
只显示 {0:{}, 1:{}}
通过使用 FormData 接口并修改 React Form 上的 onSubmit 函数使其工作。这是为遇到相同问题的任何人提供的代码:
const onSubmit = async (formData) => {
const formDataObj = new FormData();
formDataObj.append("title", formData.title);
formDataObj.append("price", formData.price);
for (const file of formData.img) {
formDataObj.append("img", file);
}
try {
const res = await axios.post(
`${import.meta.env.VITE_BACKEND_URL}/stamps`,
formDataObj,
{
headers: {
Authorization: authHeader,
},
}
);
} catch (e) {
console.log(e);
}