I was wondering whether there is a way to dynamically display an image that a user just uploaded to the input type="file" field.
For example, so far I have the following code:
image_upload.html
<form id ="image_upload_form" action="" method="post" enctype="multipart/form-data">
<input id ="id_iamge" type="file" name="image" />
<input type="submit" value="Upload" />
</form>
<div id="image_view">
<img id="uploaded_image">
</div>
upload.js
$(document).ready(function() {
$("#id_image").change(file_select);
});
function file_select(event) {
$("#uploaded_image").attr("src", $("#id_image").val());
}
So I basically want to show the image that the user just uploaded on the Field.
Of course, I know I can easily view the image if the user already SUBMITTED the form, and when the image is already inside my Database server.
However, I want to preview the image BEFORE the image is submitted into the database server.
In order to do this, I guess I have to find out the PATH of the Image in the Uploader's own computer and then set that "Local path" as the "src" of the image.
Is there a way to fetch this LOCAL PATH of the image that the user just submitted?
(My Javascript code above obviously didn't work, since it just sets the NAME of the image file, not the absolute Path, as the "src". For example, when I run that code and upload an image, I get this:
The Result:
<img id="uploaded_image" src="random_image.jpg" />
which doesn't show anything.
Take a look at this sample, this should work: http://jsfiddle.net/LvsYc/
HTML:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
JS:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
Use this code. It will work:
<!-- Java script code, use jquery library. -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
function showimagepreview(input)
{
if (input.files && input.files[0])
{
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#imgDisplayarea').attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
</script>
<!-- HTML -->
<form>
<div>
<input type="file" name="imgShow" id="imgShow" onchange="imagePreview(this)" />
</div>
<img id="imgDisplayarea"/>
</form>
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