How to upload a file using Ajax

File upload is a common feature in many web applications that was originally done using web forms with enctypemultipart/form-data. However, with the growing use of Single Page Applications, which run on AJAX requests, Ajax file upload has become necessary. In this Edpresso shot, you’ll learn how to upload files using Ajax.

Example: Ajax file upload

The example below shows a file picker that returns the size of uploaded files.

Console

How it works

First, an onchange event listener is attached to the file picker:

Console

Then, the file is obtained from the event object the listener provides – the first file in the files array is picked because we are dealing with single files.

Next, an Ajax call is made to the endpoint that expects a file upload. In this case, the file is: https://express-file-server.vicradon.repl.co/upload.

Further logic, like notifying, the user can be done in the .then block. If any HTTP errors are encountered, they are handled in the .catch block.

Console

Free Resources