I'm building a basic social network and in the registration the user uploads a display image. Basically I wanted to display the image, like a preview on the same page as the form, just after they select it and before the form is submitted.
Is this possible?
The most efficient way would be to use URL. createObjectURL() on the File from your <input>. Pass this URL to img. src to tell the browser to load the provided image.
The <input type="image"> defines an image as a submit button. The path to the image is specified in the src attribute.
Using type="file" and accept="image/*" (or the format you want), allow the user to chose a file with specific format. But you have to re check it again in client side, because the user can select other type of files.
Here is the complete example for previewing image before it gets upload.
HTML :
<html> <head> <link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" /> <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script> <meta charset=utf-8 /> <title>JS Bin</title> <!--[if IE]> <script src="http://goo.gl/r57ze"></script> <![endif]--> </head> <body> <input type='file' onchange="readURL(this);" /> <img id="blah" src="#" alt="your image" /> </body> </html>
JavaScript :
function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah') .attr('src', e.target.result) .width(150) .height(200); }; reader.readAsDataURL(input.files[0]); } }
I found This simpler yet powerful tutorial which uses the fileReader
Object. It simply creates an img element and, using the fileReader object, assigns its source attribute as the value of the form input
function previewFile() { var preview = document.querySelector('img'); var file = document.querySelector('input[type=file]').files[0]; var reader = new FileReader(); reader.onloadend = function () { preview.src = reader.result; } if (file) { reader.readAsDataURL(file); } else { preview.src = ""; } }
<input type="file" onchange="previewFile()"><br> <img src="" height="200" alt="Image preview...">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With