How to AJAX File Upload

In this tutorial on how to AJAX file upload, we will upload multiple files using AJAX and show the preview of the files when they will be uploading and when uploaded. We will use HTML, JavaScript, PHP and CSS to create the AJAXfile upload function.


Step 1: Markup and Styling

To get started on How to AJAX file upload, we will first have to start with the markup and styling. In this step, we will create a form that will post to upload.php. We have chosen the input type as file and the attributes as “multiple” so that the user can select multiple files for upload.

Markup and Styling code

Step 2: Implementing the CSS

The second step is the CSS. It is being used for the styling of the elements.

CSS code

Step 3: Implementing the PHP

Next step is to implement the PHP for the upload function. The PHP code will allow the user to select multiple files at once and upload them. Once the files have been successfully uploaded, the user will be shown a message that “Images have been uploaded successfully”.

The PHP upload function code

Step 4: Implementing the JavaScript

The most important step is the JavaScript. We have created a function which contains two variables “input” and “data”. The variable input is the file input element and the variable data is used to send the images to the server. After this, we have created a new object called “FormData”. Another helper function has been made which will show the uploaded images at the screen. This function simply takes a source as a function argument and creates a list appending the parameter source.

The JavaScript Code

Step 5 :Check for file if it is an image

Lastly, we have to create a function which will actually upload and display the image. We have to make sure that the file requested by the user is actually an image, so we will do that by comparing the type property of the file.

Comparing file type

Step 6 : Create a URL for the image

To create a URL for our image, we create a Filereader object. We also have to check if our browser supports and lets us create the object. If it supports, we pass our file object to the reader.readAsDataURL. This method will create a URL for the image that was uploaded.

URL for the image

Step 7: Outcome

When all parts of the code are joined, the ajax file upload function has been successfully created. When the user loads the page, he can easily select files using upload button and the browser will display them once they have been uploaded.

images uploaded