mirov
mirov

Reputation: 25

Upload multiple files/images, fetch, formData

I want to upload images through fetch(). I used formData and succeeded to upload, but only one image at a time.

handleGetNewPictureDragDrop = data => {

        console.log(data);

        const formData = new FormData();

        for (let i = 0; i < data.length; i++) {
            formData.append('filename', data[i]);
        }

        console.log(...formData);

        const name = this.props.nameCategory;

        fetch('http://api.../gallery/' + name, {
            method: 'POST',
            body: formData,
        })
            .then(response => response.json())
            .then(success => console.log(success))
            .catch(error => console.log(error));
    }

console.log(data):

console.log(...formData):

console.log(success):

I take 3 images, create formData, there are 3 images but after POST-ing this formData I get uploaded only one.

Upvotes: 0

Views: 5083

Answers (3)

oelna
oelna

Reputation: 2446

I had a similar problem, but with a PHP backend. The unique formData keys work, but I found that the classic HTML notation worked just fine and simply results in an array on the server.

formData.append('file[]', data[i]);

I like that a lot better, since I can use the same methods to process this as with a classic <input type="file" multiple />.

Upvotes: 1

Fatherjacob
Fatherjacob

Reputation: 184

I think you are passing the same 'name' to append for each image. the Syntax should be

formData.append(name, value, filename);

and that first one should be the field name, and if not unique, it overwrites.

try making it dynamic

  for (let i = 0; i < data.length; i++) {
        formData.append(`filename_${i}`, data[i]);
    }

or probably something else (unique from your data) would be better, just don't pass the same name for each image.

Upvotes: 1

Gurwinder
Gurwinder

Reputation: 509

Please use unique key while appending multiple files to form data.

formData.append('file'+i, data[i]);

Upvotes: 1

Related Questions