Use jQuery to preview thumbnails before uploading images
JQuery code
01 |
$( "#uploadImage" ).on( "change" , function (){ |
02 |
// Get a reference to the fileList |
03 |
var files = !! this .files ? this .files : []; |
05 |
// If no files were selected, or no FileReader support, return |
06 |
if (!files.length || !window.FileReader) return ; |
08 |
// Only proceed if the selected file is an image |
09 |
if (/^image/.test( files[0].type)){ |
11 |
// Create a new instance of the FileReader |
12 |
var reader = new FileReader(); |
14 |
// Read the local file as a DataURL |
15 |
reader.readAsDataURL(files[0]); |
17 |
// When loaded, set image data as background of div |
18 |
reader.onloadend = function (){ |
20 |
$( "#uploadPreview" ).css( "background-image" , "url(" + this .result+ ")" ); |
The following is an HTML code that contains a div that displays thumbnails and a file input field.
HTML code
1 |
< div id = "uploadPreview" ></ div > |
2 |
< input id = "uploadImage" type = "file" name = "photoimage" class = "fimg1" onchange = "PreviewImage();" /> |
Set CSSwa for our thumbnails.
CSS code
1 |
<strong>#uploadPreview { |
4 |
background-position : center center ; |
5 |
background- size : cover; |
6 |
border : 4px solid #fff ; |
7 |
-webkit-box-shadow: 0 0 1px 1px rgba( 0 , 0 , 0 , . 3 ); |
8 |
display : inline- block ;</strong> |