Reputation: 41219
Is this possible to display an image on the currunt browser session without uploading it to the server?
I am trying to display an image on my php page when users enter the upload button ,the uploaded image will temprory appear on the target url.
Here is my html form
<form action="demo.php"method="post"enctype="multipart/form-data">
<input type="file"name="uf">
<input type="submit"value="upload">
</form>
And the target file :
<?php
$pic=$_FILES["uf"]["name"];
echo "<img src='$pic'>";
It doesnt display the image. So is this somehow possible to display the image the way I am doing it?
Any help is much appriciated!
THANKS!
Upvotes: 0
Views: 1464
Reputation: 2569
You can convert the image into base64, see http://www.motobit.com/util/base64/css-images-to-base64.asp .
It will generate an <img />
like this: <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAA// lot more characters" />
It is, in my mind, a bad practice, since your browser cache the images in order to avoid to send lots of requests for an image he already has.
In php:
$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
(taken from) How to convert an image to base64 encoding?
Upvotes: 1
Reputation: 1317
Here you go: http://jsfiddle.net/LvsYc/
html:
<form method="post" enctype="multipart/form-data">
<input type="file" id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
js (requires jQuery):
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);
});
Upvotes: 2