Home > Blockchain >  I am getting empty array when I try to upload multiple images to my backend
I am getting empty array when I try to upload multiple images to my backend

Time:02-20

I have created an API in the backend which will store images to the database, I created a function for uploading the images but I get an empty array to my database.

If I do like it this way it's working fine:

<form action='http://localhost:5000/addProduct' method='post' encType='multipart/form-data'>
                <input
                    type="file"
                    name="images"
                    multiple
                    onChange={e => setImages(e.target.files)}
                    accept="image/png , image/jpeg, image/webp"
                />

                <div className=" py-3 text-right ">
                    <button type="submit" className="inline-flex justify-center py-2 px-4 border border-transparent drop-shadow-md text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Publish</button>
                </div>
            </form>

But instead of action if I create a function for uploading files I got an empty array. On the backed I receive [object FileList]

<form onSubmit={handleUploadImages }>
<input
      type="file"
      name="images"
      onChange={setImages}
      multiple
      accept="image/png , image/jpeg, image/webp"/>
<button type="submit">Publish</button>
</form>

This is the function that I created. The problem is I think here formData.append('images', images.target.files), I think I need to send the files in a different way but confused How can I do it.

    const [images, setImages] = useState<any>()
    const [data, setData] = useState()

    console.log(data);

    const handleUploadImages = (e: any) => {
        e.preventDefault()
        const formData = new FormData();
        formData.append('images', images.target.files) // problem

        fetch('http://localhost:5000/addProduct', {
            method: 'post',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.insertedId) {
                    alert('img Added')
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });

    }

CodePudding user response:

You are wrong now in append method. You have to loop thru the files and append it with images[] key. https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#example

Like:

const formData = new FormData();
const files = images.target.files;
for (let i = 0; i < files.length; i  = 1) {
   formData.append('images[]', files[i]);
}
  • Related