Languages
[Edit]
EN

JavaScript - get file upload progress

14 points
Created by:
Kate_C
22300

In this article we would like to show how to get file upload progress in JavaScript.

File upload progress in JavaScript.
File upload progress in JavaScript.

Note: select some e.g. 5 MB - 100 MB file to see effect.

// ONLINE-RUNNER:browser;

<html lang="en">
<body>
  <form id="form">
    <input name="picture" type="file" />
    <button id="submit">Upload</button>
  </form>
  <script>

	var formElement = document.querySelector('#form');
	var pictureElement = document.querySelector('#picture');
	var submitElement = document.querySelector('#submit');
	var responseElement = document.querySelector('#response');

	submitElement.onclick = function(event) {
      	event.preventDefault();

		var xhr = new XMLHttpRequest();

		if (xhr.upload) {
			xhr.upload.onprogress = function(event) {
				if (event.lengthComputable) {
                    // progress in format: 100.00
					var progress = 0.01 * Math.round(10000 * event.loaded / event.total);
					console.log('Upload progress=' + progress + '%');
				}
			};
		}

		xhr.onreadystatechange = function () {
			if (xhr.readyState == XMLHttpRequest.DONE) {
				if (xhr.status == 200) { // HTTP status 200 received
					console.log('Upload completed!');
					console.log('Response: ' + xhr.responseText);
				} else {
					console.log('Upload error (status=' + xhr.status + ')');
				}
			}
		};
		
		var data = new FormData(formElement);
		
		// or:
		// var data = {
		//    // some fields here ...
		// };

		xhr.open('POST', '/gallery/upload', true);
		xhr.send(data);

		console.log('Upload started!');
	};

  </script>
</body>
</html>
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join