Upload multiple images using FormData Web API

Upload multiple images using FormData Web API

I always knew I could only a single image in javascript using FormData web API. But turns out, I was wrong, kind of, you can upload multiple images using the FormData web API. This API helps to construct key/value pairs, which can then be sent to the server using HTTP.

Let create an input to take user clicks.

<form enctype="multipart/form-data">
      <input type="file" multiple onchange="onClickFileUpload()" id="fileUpload" />
</form>

Note:

  • we have a property called multiple in the input. This will allow users to select multiple files to upload.
  • The enctype, specifies how the form-data should be encoded when submitting to the server, and enctype="multipart/form-data" ensures no characters will be encoded.

we know need javascript to make the input interactive

<script>
        function onClickFileUpload() {
            const element = document.getElementById("fileUpload");
            const files = element.files // this will be an array. Do what you want with this files.
        }
</script>

You only need to send the files array to the server. this will depend on how your server expects this data format if as an array you safe, if other formats, you've to convert to the required format.

Did you find this article valuable?

Support Nicanor Talks Web by becoming a sponsor. Any amount is appreciated!