Languages
[Edit]
EN

JavaScript - upload dynamically file with iframe and php server

11 points
Created by:
Elias999
759

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

File upload with hidden iframe.
File upload with hidden iframe.

File upload with iframe callback example

upload.htm file:

// ONLINE-RUNNER:browser;

<html>
<head>
  <script>

	window.Uploader = function(form, frame) {
		var self = this;

		if (form.getAttribute('target') !== frame.getAttribute('name')) {
			throw new Error('Form is not linked with target frame.');
		}

		frame.addEventListener('load', function() {
			frame.contentWindow.onsuccess = function(message) {
				form.reset();
				if (self.onsuccess) {
					self.onsuccess(message);
                }
			};
			frame.contentWindow.onerror = function(message) {
				if (self.onerror) {
					self.onerror(message);
                }
			};
		});

		frame.addEventListener('error', function() {
			if (self.onerror) {
				self.onerror('Loading error.');
            }
		});
	};

  </script>
</head>
<body>
  <form id="upload-form" action="backend.php" target="upload-frame" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="Submit" />
  </form>
  <iframe id="upload-frame"  name="upload-frame" style="display:none;">
  </iframe>
  <div id="upload-result"></div>
  <script>

		var form = document.querySelector('#upload-form');
		var frame = document.querySelector('#upload-frame');
		var result = document.querySelector('#upload-result');

		var uploader = new Uploader(form, frame);

		uploader.onsuccess = function(message) {
			result.innerHTML = '<div style="color: green;">' 
				+ 'Success: ' + message 
				+ '</div>';
		};

		uploader.onerror = function(message) {
			result.innerHTML = '<div style="color: red;">' 
				+ 'Error: ' + message 
				+ '</div>';
		};

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

backend.php file:

<html>
<body>
  <script>

	function execute() {
		function action() {
			if (window.onsuccess && window.onerror) { // if event methods appeared
<?php

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

	if($_SERVER['REQUEST_METHOD'] === 'POST')
	{
		if(isset($_FILES['file']))
		{
			$file = $_FILES['file'];

			if(empty($file['name']))
				echo "window.onerror('File does not exist!');";

			else
			{
				$src_path = $file['tmp_name'];
				$dst_path = DST_DIR . $file['name'];

				if(move_uploaded_file($src_path, $dst_path))
					echo "window.onsuccess('File upload completed.');";

				else
					echo "window.onerror('File move error!');";
			}
		}
		else
			echo "window.onerror('File does not exist!');";
	}
	else
		echo "window.onerror('Unsupported request method!');";

?>
			} else {
				execute();
			}
		}

		setTimeout(action, 100);
	}

	execute();

  </script>
</body>
<html>

Notes:

  • upload.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

See also

  1. JavaScript - how to upload file with jQuery?

Merged questions

  1. JavaScript - how to upload dynamically file with iframe and php backend?
  2. JavaScript - how to send file to iframe?
  3. 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