Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML input type=file, get the image before submitting the form

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?

like image 605
Tom Avatar asked Apr 27 '11 10:04

Tom


People also ask

How do I display an image before uploading HTML?

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.

How do you take a picture input in form?

The <input type="image"> defines an image as a submit button. The path to the image is specified in the src attribute.

How do I import an image into an input type file?

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.


2 Answers

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]);   } } 
like image 67
Hardik Sondagar Avatar answered Sep 29 '22 07:09

Hardik Sondagar


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...">
like image 26
Cedric Ipkiss Avatar answered Sep 29 '22 08:09

Cedric Ipkiss