简体   繁体   中英

How do I post an Array of images using formdata reactjs

I am trying to post an object with multiple images as an array how do append the images as an array to the formdata

const onSubmit = async (e) => {

    
    const formData = new FormData(); 
    formData.append("image", values.images);
    formData.append("title", values.title);
    formData.append("price", values.price);
    formData.append("quantity", values.quantity);
    formData.append("id", id);

    try {
      const res = await axios.post(
        "//localhost:4000/products/saveProduct",
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
     /////////////
<form onSubmit={handleSubmit(onSubmit)}>
        <div className="custom-file mb-4">
          <input
            type="file"
            className="custom-file-input"
            name="image"
            multiple
            placeholder="choose file"
            onChange={handleChange}
          />
//////
  const handleChange = (e) => {
    const { type, name } = e.target;
    const getValue = () => {
      if (type === "checkbox") {
        return e.target.checked;
      } else if (type === "select-multiple") {
        return Array.from(e.target.selectedOptions).map(
          (option) => option.value
        );
      } else if (type === "file") {
        for (let i = 0; i < e.target.files.length; i++) {
          e.target.files[i].url = URL.createObjectURL(e.target.files[i]);
        }
        return Array.from(e.target.files);
      }
      return e.target.value;
    };

Also When I send this to my back end I am getting to an empty object as the req.body

You can append all the images to the same key, for example "images". Then you can parse the request body as multipart formdata on the server, and you get an array of files when you access "images".

for (const image of value.images) {
  formData.append("images", image);
}

Although, if I remember correctly. When you only append one file, it not going to be parsed into an array on the server.

Another solution is to create (with useRef) or get (with querySelector) a reference to the form element. Then you can create the formData directly from the form element.

const formData = new FormData(myFormElement);

Then you can append the rest of the data that you want to send.

for (const image of value.images) {
  formData.append("images",JSON.stringify(image));
}

when pass multiple image make string object using JSON.stringify(Object)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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