【问题标题】:MulterError: Unexpected field error while uploading image from React jsMulterError:从 React js 上传图像时出现意外的字段错误
【发布时间】:2023-02-20 22:32:25
【问题描述】:

所有与此错误相关的答案都针对检查名称upload.single("image") 和客户端输入的文件的名称属性,在我的情况下与 multer 的“图像”相同。但它仍然给出错误。

以下是节点js代码:

const Imagestorage = multer.memoryStorage()
 const upload = multer({ storage: Imagestorage })

app.post("/newpost", upload.single("image"), async(req, res) => {

     console.log(req.body);
     console.log(req.file);

let data={}
   // convert base64 image data to string using datauri/parser, upload to cloudinary and send response

  const extName = path.extname(req.file.originalname).toString();
  const file64 = parser.format(extName, req.file.buffer);
  const filename=file64.content

  cloudinary.uploader.upload(filename, async(error, result) => {
    if (error) {
      res.status(500).send("error in uploading file to cloudinary"+error);
    } else {
      // result.secure_url is the URL of the uploaded file on Cloudinary
      console.log(result.secure_url);

        let Imageurl=await result.secure_url
          data={
             name: req.body.name,
             location:req.body.location,
             likes:req.body.likes,
             description:req.body.description,
              image:Imageurl
            }
             console.log(data)
             let postedData=await postsModel.create(data)
             res.json({
                status:"ok",
                postedData
             })
        }
     });


   });

//error field in case something happens with multer
//   app.use((error, req, res, next) => {
//   console.log('This is the rejected field ->', error.field);
// });


 app.get("*", (req, res) => {
    res.status(404).send("PAGE IS NOT FOUND");
})

前端代码-

  import axios from "axios";
  import { useNavigate } from "react-router-dom";

  const Form = () => {
  const navigate = useNavigate();

  function handleSubmit(event) {
    event.preventDefault();

   
    const formData = new FormData(event.target);

    // Append the file input to the form data
    const imageFile = formData.get("image");
    formData.append("image", imageFile);
  
    // Use Axios to send a POST request to your server with the form data
    axios
      .post("https://instabackend-gcwk.onrender.com/newpost", formData, {
        //.post("http://127.0.0.1:5000/newpost", formData, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      })
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.error(error);
      })
      .finally(navigate("/insta"));
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label htmlFor="image">Image:</label>
        <input type="file" id="image" name="image" accept="image/*" />

        <button type="submit">Submit</button>
      </form>

      <button onClick={() => navigate(-1)}>Go Back Home</button>
    </div>
  );
};
export default Form;


当我尝试 -

   app.use((error, req, res, next) => {
   console.log('This is the rejected field ->', error.field);
});

它给出的错误字段为“这是被拒绝的字段 -> 图片” 注意:获取数据没有问题

【问题讨论】:

  • 你可以添加你的前端代码吗?
  • @NeNaD 添加了前端代码
  • 图片上传在邮递员中工作但不是通过反应
  • 嗯...您可以在将其发送到服务器之前尝试console.log(formData)。我不确定你在那里做了什么,但也许 formData 没有正确发送。
  • formData 与文件详细信息及其相关方法应该是一样的。反应中的错误是AxiosError: Request failed with status code 500,这是相同的服务器端多重错误。有关更多详细信息,请参见此处-Link

标签: node.js reactjs multer


【解决方案1】:

用一组 FormData() 替换 append 使代码工作。 Javascript.info explains the working of formData() here

import axios from "axios";

const App = () => {
  function handleSubmit(event) {
    event.preventDefault();

    const formData = new FormData(event.target);

    //get image
    const imageFile = formData.get("image");
    //set image
    formData.set("image", imageFile);

    axios
      .post("https://instabackend-gcwk.onrender.com/newpost", formData, {
        
        headers: {
          "Content-Type": "multipart/form-data"
        }
      })
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.error(error);
      });
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label htmlFor="image">Image:</label>
        <input type="file" id="image" name="image" accept="image/*" />

        <button type="submit">Submit</button>
      </form>
    </div>
  );
};
export default App;

【讨论】:

    猜你喜欢
    • 2019-07-12
    • 2023-03-25
    • 2021-08-15
    • 2021-05-06
    • 1970-01-01
    • 2016-09-03
    • 2021-02-05
    • 2021-02-22
    • 1970-01-01
    相关资源
    最近更新 更多