skip to Main Content

I’m trying to make a upload image feature in my website. I’ve worked on uploading a single image and it worked how do I change my code to make it upload multiple images at same time code below:

Server Side:

    // img storage confing
    var imgconfig = multer.diskStorage({
        destination: (req, file, callback) => {
            callback(null, "./uploads");
        },
        filename: (req, file, callback) => {
            callback(null, `image-${Date.now()}.${file.originalname}`)
        }
    });
    
    
    // img filter
    const isImage = (req, file, callback) => {
        if (file.mimetype.startsWith("image")) {
            callback(null, true)
        } else {
            callback(null, Error("only image is allowd"))
        }
    }
    
    var upload = multer({
        storage: imgconfig,
        fileFilter: isImage
    })
    
    
    
    // register userdata
    app.post("/insertImage", upload.single("photo"), (req, res) => {
        const { filename } = req.file;
        
        console.log(req.file)
    });

Client Side:

      const [file, setFile] = useState("");
    
      const setimgfile = (e) => {
        setFile(e.target.files[0])
      }
    
      const addUserData = async (e) => {
        e.preventDefault();
    
        var formData = new FormData();
        formData.append("photo", file)
    
        const config = {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        }
    
        const res = await Axios.post("/insertImage", formData, config);
    
        if (res.data.status == 201) {
          console.log("NO error")
        } else {
          console.log("error")
        }
      }

REACT JSX

Here is my input file and multiple is added here

    <div style={{ padding: 15, backgroundColor: '#fff', marginTop: 15 }}>
                <h4>Upload file:</h4>
                <input type="file" name='photo' onChange={setimgfile} multiple/>
                <button onClick={addUserData}>submit</button>
    </div>

2

Answers


  1. Push all your files in your formdata using a loop, and the same thing to create the received files in disk.
    dont forget to use multiple

    <input type="file" id="fileInput" multiple />
    

    for more details check this example https://www.freecodecamp.org/news/formdata-explained/

    Login or Signup to reply.
  2. Server code

    app.post("/insertImages", upload.array("photos"), (req, res) => {
        console.log(req.files)
    });
    

    Note: When uploading multiple images, Multer will populate req.files, and not req.file.


    Client code

    const formData = new FormData();
    
    selectedImages.forEach((image, index) => {
      formData.append(`photos[${index}]`, image)
    })
    
    <input type="file" name="photos" multiple>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search