preview image before upload

Preview image from input type file before upload – Javascript

0
(0)

In this article, we will learn how to preview image before upload from input type file using Javascript. A FileReader object is used.

The following code will display an input type file from where the user can select an image file. As soon as he selects the image, it’s preview will be displayed in an image tag. This is useful when you want to show the user the image he selected, before saving it in the database. So the user must know that he has picked the correct image.

<script>
	function previewImage() {
		var file = document.getElementById("file").files;
		if (file.length > 0) {
			var fileReader = new FileReader();

			fileReader.onload = function (event) {
				document.getElementById("preview").setAttribute("src", event.target.result);
			};

			fileReader.readAsDataURL(file[0]);
		}
	}
</script>

<form method="POST" action="/" enctype="multipart/form-data">
	<input type="file" name="file" id="file" accept="image/*" onchange="previewImage();">

	<img id="preview">
</form>

Explanation

Form encoding type will be used to upload the file on the server-side (PHP). Give your input type file a unique ID so it can be accessed in Javascript. We have created an image tag where a preview of the selected file will be displayed. Give a unique ID to this image tag too. A function on onchange event on input type file will be called whenever user select some file from dialog. We are also adding an attribute accept=”image/*” that will make sure that the user selects only the image files like JPEG, PNG etc.

In this function, first we are checking if the user has selected any file. We are creating a FileReader object, it is used to read the file. With this file reader object, we are calling a function named readAsDataURL, it will read the content of a file as URL. That URL will be used to set the “src” attribute of our image tag.

onload event will be called when the file is fully read by file reader object. In this function, we are simply setting the “src” attribute of our image tag. event.target refers to the original file reader object and “result” is the actual URL of selected file.

Since you have learned how you can preview an image before upload from input type file using Javascript. Learn also how to upload, download and delete files in PHP.

How useful was this post

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post





Leave a Reply

Please disable your adblocker or whitelist this site!