LogoLoading Please Wait...

Preview Image Files & PDF During Upload with JavaScript

By divine_admin_infosys

We all can see previews of image/pdf files in the left pane in our windows pc while we click on the file, the same way if we want to show a preview of files before uploading them to the server, how can we do that? So here I am showing a way how to do that, In the first snippet, we will see how can we preview images and then in the second snippet we will see how to preview pdf files.

Preview Image Files

First, we have to include jquery to make the below example run fine.

https://code.jquery.com/jquery-3.4.1.min.js

HTML CODE

<h2>Image Preview</h2>
<label>Select a file (jpg, jpeg, png)</label><br/>
<div><input type="file"/></div>

JAVASCRIPT CODE

On the Change event of the file, we will call the function. FileReader() will be used in this.

$(document).ready(function () {
	var fileTypes = ['jpg', 'jpeg', 'png'];  //acceptable file types
	$("input:file").change(function (evt) {
	    var parentEl = $(this).parent();
	    var tgt = evt.target || window.event.srcElement,
	                    files = tgt.files;

	    // FileReader support
	    if (FileReader && files && files.length) {
	        var fr = new FileReader();
	        var extension = files[0].name.split('.').pop().toLowerCase(); 
	        fr.onload = function (e) {
	        	success = fileTypes.indexOf(extension) > -1;
	        	if(success)
		        	$(parentEl).append('<img src="' + fr.result + '" class="preview"/>');
	        }
	        fr.onloadend = function(e){
	            console.debug("Load End");
	        }
	        fr.readAsDataURL(files[0]);
	    }   
	});
});

YOU CAN VIEW DEMO HERE  

 

Preview PDF Files

PDF preview can’t be done with just jquery we have to include external libraries for it, here we will use the well known library by Mozilla pdf.js

In this example, we will preview only first page of the PDF.

https://code.jquery.com/jquery-3.4.1.min.js

https://mozilla.github.io/pdf.js/build/pdf.js

HTML CODE

<input type="file" id="myPdf" />
<canvas id="pdfViewer">

JAVASCRIPT CODE

// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.js';

$("#myPdf").on("change", function(e){
	var file = e.target.files[0]
	if(file.type == "application/pdf"){
		var fileReader = new FileReader();  
		fileReader.onload = function() {
			var pdfData = new Uint8Array(this.result);
			// Using DocumentInitParameters object to load binary data.
			var loadingTask = pdfjsLib.getDocument({data: pdfData});
			loadingTask.promise.then(function(pdf) {
			  console.log('PDF loaded');
			  
			  // Fetch the first page
			  var pageNumber = 1;
			  pdf.getPage(pageNumber).then(function(page) {
				console.log('Page loaded');
				
				var scale = 1.5;
				var viewport = page.getViewport({scale: scale});

				// Prepare canvas using PDF page dimensions
				var canvas = $("#pdfViewer")[0];
				var context = canvas.getContext('2d');
				canvas.height = viewport.height;
				canvas.width = viewport.width;

				// Render PDF page into canvas context
				var renderContext = {
				  canvasContext: context,
				  viewport: viewport
				};
				var renderTask = page.render(renderContext);
				renderTask.promise.then(function () {
				  console.log('Page rendered');
				});
			  });
			}, function (reason) {
			  // PDF loading error
			  console.error(reason);
			});
		};
		fileReader.readAsArrayBuffer(file);
	}
});

YOU CAN VIEW DEMO HERE  

Divine Infosys