multer和formik-可以上传文件
我对Multer和Formik有问题。当我与Postman测试我的上传路由,将图像上传到帖子中,它可以完美地工作,将ImageUrl保存在MySQL中,然后将图像保存在正确的文件夹中。但是,当我尝试使用formik的真实前端执行此操作时,文件只是不想将其上传为文件,而只是作为字符串。但是形式具有“ enctype = multipart/form-data”。
npm给我此错误消息:
“图像:req.file.path,
typeError:无法阅读未定义的属性(阅读'path')“
我现在整天都在努力,所以我将把所有需要向您解释我的问题所需的一切:
路线发布配置:
router.post("/", validateToken, multer, async (req, res) => {
const postBody = {
title: req.body.title,
postText: req.body.postText,
image: req.file.path,
username: req.user.username,
UserId: req.user.id,
};
postBody.imageUrl = `${req.protocol}://${req.get("host")}/images/${
req.file.filename
}`;
await Posts.create(postBody);
res.json(postBody);
});
前端formik part:
<Formik
initialValues={initialValues}
onSubmit={onSubmit}
validationSchema={validationSchema}
>
<Form
className="formContainer"
action="/"
encType="multipart/form-data"
>
<label>Title: </label>
<ErrorMessage name="title" component="span" />
<Field autoComplete="off" name="title" placeholder="(Ex. Title...)" />
<label>Post: </label>
<ErrorMessage name="postText" component="span" />
<Field
autoComplete="off"
name="postText"
placeholder="(Ex. Post...)"
/>
<input type="file" name="image"></input>
<button type="submit"> Create Post</button>
</Form>
</Formik>
axios axios part:
const onSubmit = (data) => {
console.log(data);
axios
.post("http://localhost:3001/posts", data, {
headers: {
accessToken: localStorage.getItem("accessToken"),
"content-type": "multipart/form-data",
},
})
.then((response) => {
console.log(data);
navigate("/");
});
};
和数据控制台。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您没有使用formik字段来获取文件输入,因此请尝试设置
onChange
手动,然后使用on Change Handler更新Formik状态。类似:
setField
是一个formik函数,应该允许您将其赋予实际文件。 Formik似乎并不是本地支持文件,因此似乎有必要使用此解决方法。链接:
codesandox
setfield
custom onChange
Since you are not using a Formik field to get the file input, try setting the
onChange
manually, and update the Formik state with an on change handler.Something like:
setField
is a formik function that should allow you to give it the actual file. Formik doesn't seem to support files natively so this workaround appears necessary.Links:
codesandox
setField
custom onChange
&lt; input type =“ file” name =“ image” onChange = {uploadfile}/&gt;
更多关于fileReader,readasdataurl,(on)loadEnd和休息,您可以在这里阅读:
<input type="file" name="image" onChange={uploadFile}/>
More about fileReader, readAsDataURL, (on)loadend, and rest, you can read here: