multer和formik-可以上传文件

发布于 2025-02-04 12:22:39 字数 2011 浏览 2 评论 0 原文

我对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("/");
  });
};

和数据控制台。

I've got a problem with multer and Formik. When I test with Postman my upload route, to upload an image in a post, it works perfectly, save the imageUrl in MySQL and save the image in the correct folder. But when I try to do this in my real front end with formik, the file just don't want to upload as a file, but only as a string. But Form has "encType=multipart/form-data".

NPM give me this error message :

"image: req.file.path,

TypeError: Cannot read properties of undefined (reading 'path')"

I'm struggling with this for one entire day now, so I will put right there everything's needed to explain to you my problem:

route post config :

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);
});

front end 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 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("/");
  });
};

And Data console.log in google inspector :

data console.log

Thx in advance guys !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我偏爱纯白色 2025-02-11 12:22:39

由于您没有使用formik字段来获取文件输入,因此请尝试设置 onChange 手动,然后使用on Change Handler更新Formik状态。

类似:

<input 
  type="file" 
  name="image"
  onChange{(e) => {
    setField("image", e.target.files[0])
  }}
/>

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:

<input 
  type="file" 
  name="image"
  onChange{(e) => {
    setField("image", e.target.files[0])
  }}
/>

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

数理化全能战士 2025-02-11 12:22:39

&lt; input type =“ file” name =“ image” onChange = {uploadfile}/&gt;

const [file, setFile] = React.useState();

const uploadFile = (event) => {
  if (!event.target.files?.length) return;
  const fileReader = new FileReader();
  const file = event.target.files[0];
  fileReader.readAsDataURL(file);

  fileReader.onloadend = () => {
  const content = fileReader.result;
  if (content) {
    setFile(content); 
  }
};

更多关于fileReader,readasdataurl,(on)loadEnd和休息,您可以在这里阅读:

<input type="file" name="image" onChange={uploadFile}/>

const [file, setFile] = React.useState();

const uploadFile = (event) => {
  if (!event.target.files?.length) return;
  const fileReader = new FileReader();
  const file = event.target.files[0];
  fileReader.readAsDataURL(file);

  fileReader.onloadend = () => {
  const content = fileReader.result;
  if (content) {
    setFile(content); 
  }
};

More about fileReader, readAsDataURL, (on)loadend, and rest, you can read here:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文