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?
This question is related to
javascript
html
forms
file-io
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() {_x000D_
var preview = document.querySelector('img');_x000D_
var file = document.querySelector('input[type=file]').files[0];_x000D_
var reader = new FileReader();_x000D_
_x000D_
reader.onloadend = function () {_x000D_
preview.src = reader.result;_x000D_
}_x000D_
_x000D_
if (file) {_x000D_
reader.readAsDataURL(file);_x000D_
} else {_x000D_
preview.src = "";_x000D_
}_x000D_
}
_x000D_
<input type="file" onchange="previewFile()"><br>_x000D_
<img src="" height="200" alt="Image preview...">
_x000D_
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]);
}
}
Image can not be shown until it serves from any server. so you need to upload the image to your server to show its preview.
this can be done very easily with HTML 5, see this link http://www.html5rocks.com/en/tutorials/file/dndfiles/
I feel we had a related discussion earlier: How to upload preview image before upload through JavaScript
Source: Stackoverflow.com