Javascript AJAX File Upload With Progress Bar

javascript
Published on February 4, 2018

Files can be uploaded from a browser using Javascript's XMLHttpRequest & FormData objects.

File uploading in Javascript can be achieved by :

  • Choosing a file from the system using a <input type="file" /> tag.
  • Validating chosen file for type and size.
  • Sending a POST request using the XMLHttpRequest object with the file attached.

Step 1 — Choose a Local File

<input type="file" id="file-input" />
<button id="upload-button">Upload File</button>
  • To allow multiple files to be chosen, set the multiple attribute.

    <input type="file" multiple />
    
  • Restrictions on file types can be set by specifying the required MIME type in the accept attribute (although it is possible for the user to override it). Each allowed MIME type needs to be separated by a comma.

    <!-- Allow only JPEG & PNG files to choose -->
    <input type="file" accept="image/jpeg, image/png" />
    

Step 2 — Validate Chosen File for Type and Size

document.querySelector('#upload-button').addEventListener('click', function() {
	// user has not chosen any file
	if(document.querySelector('#file-input').files.length == 0) {
		alert('Error : No file selected');
		return;
	}

	// first file that was chosen
	var file = document.querySelector('#file-input').files[0];

	// allowed types
	var mime_types = [ 'image/jpeg', 'image/png' ];
	
	// validate MIME type
	if(mime_types.indexOf(file.type) == -1) {
		alert('Error : Incorrect file type');
		return;
	}

	// max 2 MB size allowed
	if(file.size > 2*1024*1024) {
		alert('Error : Exceeded size 2MB');
		return;
	}

	// validation is successful
	alert('You have chosen the file ' + file.name);

	// upload file now
});
  • The files property of the file input DOM element is an array of file objects representing the files selected by the user.
  • type property of chosen file object gives its MIME type.
  • size property gives its size in bytes.
  • name property gives its name.

Step 3 — Send an AJAX POST Request with File Attachment

var data = new FormData();

// file selected by the user
// in case of multiple files append each of them
data.append('file', document.querySelector('#file-input').files[0]);

var request = new XMLHttpRequest();
request.open('post', 'upload.php'); 

// upload progress event
request.upload.addEventListener('progress', function(e) {
	var percent_complete = (e.loaded / e.total)*100;
	
	// Percentage of upload completed
	console.log(percent_complete);
});

// AJAX request finished event
request.addEventListener('load', function(e) {
	// HTTP status message
	console.log(request.status);

	// request.response will hold the response from the server
	console.log(request.response);
});

// send POST request to server side script
request.send(data);
  • File uploading requires multipart/form-data HTTP POST request to the server. This can be achieved by sending a FormData object.
  • The progress event of the XMLHttpRequest.upload object listens for upload progress. A upload progress bar can be created utilizing this.
  • The load event handles competition of the AJAX request.
Related Tutorials
2 Ways of AJAX File Upload - FormData and FileReader
AJAX File Download with Progress Bar in Pure Javascript
Javascript File Uploading with Fetch, Async & Await
Comments
Loading Comments