Languages
[Edit]
EN

JavaScript - upload file with jQuery

9 points
Created by:
Iona
415

In this article, we would like to show you how to upload files with jQuery in JavaScript.

jQuery file upload example

ajax.htm file:

<!doctype html>
<html lang="en">
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
  <form id="form" method="POST" onsubmit="sendForm(); return false;">
    <input type="file" id="file" />
    <input type="submit" value="Upload" />
  </form>
  <pre id="progress"></pre>
  <script>

	var file = document.getElementById('file');
	var progress = document.getElementById('progress');

	function sendForm() {
		var data = new FormData();

		var files = file.files;
		
		for (var i = 0; i < files.length; ++i) {
			data.append('file', files[i]);
		}

		$.ajax({
			type: 'POST',
			url: '/backend.php',
			data: data,
			contentType: false,
			processData: false,
			xhr: function () {
				var xhr = $.ajaxSettings.xhr();
				
				if (xhr.upload) {
					xhr.upload.onprogress = function(e) {
						var tmp = Math.round(100.0 * (e.loaded / e.total));
						
						progress.innerText = 'Uploaded ' + tmp + '%';
					};
				}
				
				return xhr;
			},
			success: function (data) {
				file.value = '';
			
				progress.innerText = data;
			},
			error: function(error) {
				progress.innerText = 'Error: ' + error.status;
			}
		});
	}

  </script>
</body>
</html>

backend.php file:

<?php

	define('DST_DIR', 'C:\\wamp64\\www\\uploaded_files\\');

	if($_SERVER['REQUEST_METHOD'] === 'POST')
	{
		if(isset($_FILES['file']))
		{
			$file = $_FILES['file'];
			
			$src_path = $file['tmp_name'];
			$dst_path = DST_DIR . $file['name'];
			
			move_uploaded_file($src_path, $dst_path);
			
			echo "File uploaded successfully.";
		}
		else
			echo "File does not exist.";
	}
	else
		echo "Unsupported request method.";

Notes:

  • ajax.htm and backend.php should be both places on same php server
  • directory path C:\wamp64\www\uploaded_files\ should be changed to own path - do not forget to put backslash at the end of path and have permission for files writing there

Result:

 jQuery file upload with php backend
 jQuery file upload with php backend

See also

  1. JavaScript - how to upload dynamically file with iframe and php server?
  2. JavaScript - how to upload file without page reloading?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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