Sending upload image contents to the server before form submission

In my previous post, I was writing about previewing images before uploading. It is handy if you want to display the uploaded image to the user before form submission. But what if you want to send such image contents to the server? Sometimes you may want to pre-process the file, check it somehow… This can be also the way to speed up the upload process – if the file is large, and the user is about to spend some time on the form – you can send the image in the background and have it handy.

So, how to do this? Once the image is selected by the user, we can read it from the disk and send it to the server using an AJAX request.

<form>
    <input type="file" id="newImage" name="newImage" accept="image/png,image/jpeg" />
</form>
<script>
    document.getElementById('newImage').onchange = function(){
        if (this.files && this.files[0]) {
            let theFile = this.files[0];
            let formData = new FormData();
            formData.append("theFileFormField", theFile);

            let xhr = new XMLHttpRequest();
            xhr.open('POST', '/url/on/the/server', true);
            xhr.send(formData);
        }
    };
</script>

The whole thing is rather easy – once the file input field is changed (on change event) we are making sure that the file is selected. As the next step, we have to prepare the form data – in the above case, we are using a single field (theFileFormField) which will contain the file. The last step is to use AJAX (XMLHttpRequest) to actually send the file to the server.

If you want to add also upload handler, just before “xhr.send” you can place something like this:

xhr.onreadystatechange = function() { 
    // making sure that the request is done and successful
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { 
        // further processing on successful upload
    }
}

I’m using this event handler to let user know that the image is uploaded, to exclude the file from further processing (since it is already uploaded), and other actions like this. Of course, you can also handle errors using the same method.