简体   繁体   English

为什么文件没有从 react-front-end 上传到后端

[英]Why files are not being uploaded in the back-end from react-front-end

Recently I started working on a project where I am using react as my front-end and node as my back-end.最近,我开始从事一个项目,在该项目中,我使用 react 作为前端,使用 node 作为后端。 In this project, I have a requirement to upload multiple images from the front-end and my back-end will receive the files and they will be uploaded in cloudinary.在这个项目中,我需要从前端上传多张图像,我的后端将接收文件并将它们上传到 cloudinary。 I have created an API route for that.我为此创建了一个 API 路由。 Which works just fine!哪个工作得很好! but when I am trying to do that same thing from my react front-end, I am not receiving any files just getting an empty [] but when I was using postman, I was receiving all the files properly inside an array.但是当我试图从我的 React 前端做同样的事情时,我没有收到任何文件,只是得到一个空的 [] 但是当我使用邮递员时,我在一个数组中正确接收了所有文件。 What is the issue here?这里有什么问题? I guess this is a problem from my front-end.我想这是我前端的问题。 But I can't figure out what is the problem.但我无法弄清楚是什么问题。

I am sharing my front-end and back-end code:-我正在分享我的前端和后端代码:-

front-end前端

const Upload = () => {
const [fileAra, setFileAra] = useState([]);

// for sending these files to the back-end
async function uploadProduct() {
    try {
      const formData = new FormData();

      formData.append("assets", fileAra);

      const res = await fetch("/get_product/post_product", {
        method: "POST",
        body: formData,
      });

      const body = await res.json();

      if (res.status === 200) {
        history.push(`/profile/${user._id}`);
        toast.dark(body.message);
      }
    } catch (err) {
      console.log(err);
    }
  }

    return (
        <input type="file" multiple onChange={(e) => setFileAra(e.target.files)} />
        <button onClick={uploadProduct}></button>
    )
}

Back-end route后端路由

router.post(
  "/post_product",
  checkAuth,
  multer.array("assets", 10),
  async function(req, res, next) {
    try {
      const pictureFiles = req.files;

      // map through images and create a promise array using cloudinary upload function
      const multiplePicturePromise = pictureFiles.map((picture) =>
        cloudinary.uploader.upload(picture.path, {
          folder: `devR-Commerce/products/${req.user.name}`,
        })
      );

      const imageResponses = await Promise.all(multiplePicturePromise);

      // separating each of the images into objects
      const allImagesSeparatedInObject = imageResponses.map((img) => ({
        photoId: img.public_id,
        photoUrl: img.secure_url,
      }));

      // creating a new product instance
      const newProduct = new Product({
        user: req.user._id,
        images: allImagesSeparatedInObject,
      });

      // saving the product in my database
      const savedProduct = await newProduct.save();

      // creating relation between these two collections: Product and User
      await User.updateOne(
        { _id: req.user._id },
        { $push: { products: savedProduct._id } }
      );

      res
        .status(200)
        .json({ message: "Product uploaded successfully", newProduct });
    } catch (err) {
      next(err);
    }
  },
);

Note: The back-end route works properly I have tested with Postman.注意:后端路由工作正常,我已经用 Postman 测试过。 But when I try to send the same files from my front-end, I don't receive any files.但是当我尝试从前端发送相同的文件时,我没有收到任何文件。 Might be a problem in the front-end.可能是前端的问题。 Please help me if you know the answer.如果你知道答案,请帮助我。 If you need any additional information about this problem, please feel free to ask.如果您需要有关此问题的任何其他信息,请随时询问。 Thanks for checking this out感谢您检查这一点

You need to append each file to the FormData one by one and not attach the whole array at once, like this.您需要将每个文件一个一个地附加到 FormData 中,而不是像这样一次附加整个数组。

async function uploadProduct() {
    try {
      const formData = new FormData();

      for (let i = 0; i < fileAra.length; i++) {
         formData.append(fileAra[i].name, fileAra[i])
      }

      const res = await fetch("/get_product/post_product", {
        method: "POST",
        body: formData,
      });

      const body = await res.json();

      if (res.status === 200) {
        history.push(`/profile/${user._id}`);
        toast.dark(body.message);
      }
    } catch (err) {
      console.log(err);
    }
  }

you can check out this article explaining FormData for further details您可以查看这篇解释 FormData 的文章以获取更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM