Mihael Keehl
Mihael Keehl

Reputation: 355

How to select multiple images separately?

I'm having trouble uploading multiple images because the array of the files get's overwritten when I only select one image at a time.

Here is the HTML I'm using:

<input type="file" id='files' name="files[]" multiple/>

I'm using Javascript to display the selected Images and I'm giving the user the option to remove them if they must.

Now let's say you select one image to upload, and select one after that as well, the Javascript will display two images. But when I use this:

$("#files")[0].files

It only displays one file, because the entire array was overwritten as the user selected two images not at once, but separately. So how can I make the user select two images separately and still get the entire list?

Upvotes: 1

Views: 1380

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92274

You have to manage that in memory separately. One field is not going to store previous values that were stored. Just like a text input field is not going to remember a previous value once you type a new value in it. See Reading client side text file using Javascript (You'll have to adapt it to binary data. See https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsArrayBuffer and Convert blob to base64)

Alternatively, after the user selects a file, create a new file input dynamically.

Upvotes: 1

boymeetscode
boymeetscode

Reputation: 825

Can you utilize the push method to append each image to the array and then pop them as needed? Basically, iterate over the array. If they select two files, it will do a push, push and done.

If they upload one image at a time, same thing will happen just more slowly.

Upvotes: 1

Related Questions