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!
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);
});
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?
Related
i have a php form and use html2pdf (TCPDF). The php form works when I use text and images that already include in the form, but now I want to attach a image and also include that in the pdf file.
The code I am using now I get the filename.
To attach the image I am using
$<span><input type="file" name="foto"></span>
And to include it in the pdf-file I use this code
$foto = $_POST['foto'];
$content .= '<img src='.$foto.'with=200 height=auto>';
Sorry for my bad English!
Regards
Daniel
Do an normal HTML file upload like this:
<form method="post" enctype="multipart/form-data">
<label>Deine Datei ;) :
<input name="fileUpload" type="file" accept="image/*">
</label>
<label>Your Name:
<input name="userName" type="text" accept="image/*">
</label>
<button type="submite" name="submite">Upload</button>
</form>
And on the PHP side you must move your file:
if(isset($_POST["submit"])) {
$userName = $_POST['userName']; // the normale methode
$check = getimagesize($_FILES["fileUpload"]["tmp_name"]);
if($check !== false) {
$temp_path_to_file = $_FILES['fileUpload']['tmp_name'];
$file_content = file_get_contents($temp_path_to_file);
// and now past your image to your PDF.
// if you want to save the image on the server you must move it with this (its not necessary if you want only to past it in your PDF)
if(move_uploaded_file($temp_path_to_file, '/my/image/folder/image_'.uniqid() . '.' . pathinfo($filename, PATHINFO_EXTENSION);
}
}
EDIT:
For your example you must convert the $file_content to an base64 string. Than you can past it in your image:
$base64 = 'data:image/' . pathinfo($filename, PATHINFO_EXTENSION) . ';base64,' . base64_encode($file_content);
echo '<img src="'. $base64 .'" style="with: 200; height: auto">';
I get this error everytime i hit the submit button. Everything else is submitted to the database, only the image isn't.
Warning: file_get_contents(): Filename cannot be empty
Any idea? Here is my code.
if(isset($_POST['consultationbutton'])){
$image = addslashes(file_get_contents($_FILES['selectedfile']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['selectedfile']['name']);
$checkedcondition = implode(",",$_POST['skincondition']);
$checkedproduct = implode(",",$_POST['skincareinuse']);
$consultquery="INSERT INTO counsel(nric,dateconsulted,editableface,skincarecurrentlyinuse,skincondition,imagename) VALUES('132','$_POST[storedate]','{$image}','$checkedproduct','$checkedcondition','{$image_name}')";
mysqli_query($dbconn,$consultquery);
// mysqli_escape_string($dbconn,$image);
echo $checkedcondition;
echo $checkedproduct;
}
<form action="BAConsult.php" enctype="multipart/form-data" method='post'>
<img id="customerface" src="#" alt="your image" class ="consultimg"></img>
Select a file to upload: <input type="file" name="selectedfile" onchange="readURL(this);">
<input type='submit' name='consultationbutton' class='consultationbutton' value='Complete Consultation' onclick='submitclick();'>
</form>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#customerface')
.attr('src', e.target.result)
.width(400)
.height(400);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
In the $_FILES array, you've said you're getting [name]=>DSC_0770.JPG[type]=> [tmp_name]=>[error]=>1[size]=>0
If tmp_name is not given, that means the file was not uploaded.
The error you're given is 1, and according to the upload error messages explained page this means: that the uploaded file exceeds the upload_max_filesize directive in php.ini.
You can do the following to fix this.
Find your php.ini file and increase the size of upload_max_filesize.
Use ini_set('upload_max_filesize', '20M'); or whatever size you want at the start of your script.
Compress your images before uploading.
make sure you add enctype="multipart/form-data" attribute in your <form> tag. like
<form action="your_action_file" method="post" enctype="multipart/form-data">
I'm trying to upload an image by submitting form. Following is my code snippet:
html:
<form method="POST" id="statusform" action="insertstatus.php" enctype="multipart/form-data">
<textarea name="statusText" onclick="javascript:this.value='';" class="retroText" style="width:600px;height:100px;font-family:lucida sans unicode,lucida grande,sans-serif;resize:none;padding:5px;">Post your crap here ...</textarea>
<input type="file" name="statusPhoto" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" size="26" />
</form>
jquery:
$("#statusform").submit(function() {
$.post($("#statusform").attr("action"), $("#statusform").serialize(), function(data){
alert(data);
});
//Important. Stop the normal POST
return false;
});
php:
if(isset($_FILES['statusPhoto']) && $_FILES['statusPhoto']['size'] > 0)
{
<Image Upload Code>
}
else
echo "Photo not submitted";
The message returned from ajax is: Photo not submitted.
Please help..!!
You are uploading, not the image, you uploading it name.
$("#statusform").serialize() return a string, image is a blob. Try to use some jQuery plugins, for example.
You can upload file asynchronously by iframe as described in article:
http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/
I am using the following loop to send/attach multiple attachments to my email message.
foreach(array_keys($_FILES['attachment']['name']) as $key) {
$source = $_FILES['attachment']['tmp_name'][$key];
$filename = $_FILES['attachment']['name'][$key]; // original filename from the client
$mail->AddAttachment($source, $filename);
}
But only the first attachment i made is sended.
The form code is
<form method="POST" action="<?php $PHP_SELF ?>" enctype="multipart/form-data">
<input type="file" name="attachment[]" id="attachment" size="30"
onchange="document.getElementById('moreUploadsLink').style.display = 'block';" />
<div id="moreUploads"></div>
<div id="moreUploadsLink" style="display:none;">
Attach another File</div>
<input name="submit" type="submit" value="submit" />
</form>
When one click on Attach another file, another File Upload button is shown, through a JavaScript function:
<script type="text/javascript">
var upload_number = 1;
var attachmentlimit = 5;
function addFileInput() {
var d = document.createElement("div");
var file = document.createElement("input");
file.setAttribute("type", "file");
file.setAttribute("name", "attachment"+upload_number);
d.appendChild(file);
document.getElementById("moreUploads").appendChild(d);
upload_number++;
if(upload_number == attachmentlimit) {
document.getElementById('moreUploadsLink').style.display='none';
}
}
</script>
Only the file attached through the first FileUpload Button is attached and sended, not the others.
Help.
The problem is that you are setting the name attribute of your new input element to attachment1, attachment2, etc. You should be setting this name to attachment[], just like the original input you created.
If you still don't get all your attachments, you can try a var_dump($_FILES) in your PHP script to ensure that you are getting all the files the way you expect them.
I am having problem uplaoding file,
here are my codes:
Any help? Thanks!
test.html
function insertPhoto()
{
var description = document.getElementById('description').value;
var image = document.getElementById('photo').value;
var url = "ajax_insert.php?action=add&image="+image+"&description="+description;
var ajaxRequest = ajax_obj();
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4){
document.getElementById("msgbox").innerHTML=ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
return false;
}
<div align="center">
<div class="top" >
<div>
Decription <input name="description" type="text" id="description" value="" maxlength="20" />
</div>
<div style="margin-top:5px" >
Image
<input name="photo" type="file" id="photo" value="" maxlength="20" />
</div>
<div class="buttondiv">
<input name="button" type="button" value="Upload" onclick="return insertPhoto()" style="margin-left:-10px; height:23px" />
<span id="msgbox" style="display:none"></span>
</div>
</div>
</div>
ajax_insert.php
<?php
mysql_connect('localhost','root','');
mysql_select_db('priceless');
define('DIR_IMAGE','images/');
$image = $_GET['image'];
$description = $_GET['description'];
$dbtable = 'photos';
$action = $_GET['action'];
if($action == 'add'){
$photo = '';
if ($_FILES[$image]['name']) {
$aray = explode(".",$_FILES[$image]['name']);
$ext = $aray[count($aray)-1];
$photo = date('Ymdhis').'.'.$ext;
move_uploaded_file($_FILES[$image]['tmp_name'],DIR_IMAGE.$photo);
}
$data = array(
'image'=> $photo,
'description'=> $description
);
$values = array();
foreach($data as $show){
$values[] = $show;
}
$query = "INSERT INTO ".$dbtable." (`".implode("`,`",array_keys($data))."`) values ('".implode("','",array_values($values))."')";
if ($result= mysql_query($query) or die(mysql_error())) {
echo "You have Sucessfully Upload Photo!";
}
}
?>
Personally I use this Ajax upload http://valums.com/ajax-upload/ and I'm satisfied with results.
You can't upload files using pure AJAX, because you can't access the file's contents programmatically due to security issues.
You can use an iframe and specify it as the target of the upload form.
You can see an example of it here: http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html
You can't upload files using pure AJAX, because you can't access the file's contents programmatically.
You would have to use a different technique, e.g. submitting the form the normal way into a hidden iframe element. That's the way the jQuery form plugin does it.
If you want some AJAXy upload, look at Uploadify - http://www.uploadify.com/
It can handle multiple uploads at once, and has a real time progress bar. It then has JS parameters to allow you to handle the upload etc.
If you need a full tutorial give me a shout and I will show you some examples!
Hope this helps.
Because of security issues, many browsers do not let you pass data from a file select field through javascript/ajax. It is better to use a page that calls itself, with a normal submit button. (I've tried AJAX uploads on my own website, so believe me).
Try -
<?php
if ($_FILE['file'] != ''){
$dest = 'folder/';
list($name, $ext) = explode('.', $_FILES['file']['name']);
if(is_uploaded_file($_FILES['file']['tmp_name'])){
#move_uploaded_file($_FILES['file']['tmp_name'], $dest.$name.'.'.$ext);
};
};
?>