I know how upload an image by a form in php. This is my php-code:
<?php
include('include/db.inc.php');
if(!isset($_SESSION))
{
session_start();
}
if(isset($_SESSION['username']))
{
$username = $_SESSION['username'];
$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
$max_size = 200 * 1024;
$path = "../php/data/users/".$username."/";
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if(!empty($_FILES['image']))
{
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
if(in_array($ext, $valid_exts) && $_FILES['image']['size'] < $max_size)
{
$path = $path . 'profile.jpg';
if (move_uploaded_file($_FILES['image']['tmp_name'], $path))
{
$sql = 'UPDATE users SET img_src = "profile.jpg" WHERE username_crypt = "'.$username.'"';
$result = mysql_query($sql) or die("Query error: ".mysql_error());
echo("Success");
}
}
else
{
echo ("InvalidFile");
}
}
else
{
echo ("FileNotUploaded");
}
}
else
{
echo ("BadRequest");
}
}
?>
After the upload, I take the uploaded image by php and the upload works.
But my question is: I have a div in HTML page where there's already an image selected by php. I would upload the new image and replace this without refresh of the page. I would upload the image and after the upload I would see the new image change the previous. I don't know how I could do that. I don't know how I can use AJAX in this context. I would obviously control the errors that php makes during the upload.
I would only click on a button that chooses the image, upload that image and then change the image div with the new uploaded picture without any refresh.
Thank you :D
You could take a look at jQuery File Upload: http://blueimp.github.io/jQuery-File-Upload/
Indeed, you need to use AJAX.
You can use this code below:
<script>
$.ajax({
type: "POST",
url: "YOUR-PHP-URL",
data: YOUR-DATA,
success: function(data){
$('YOUR-DIV').HTML(HERE-YOUR-NEW-IMAGE);
},
error: function(data){
Do-SOMETHING-IF-YOU-WANT
}
})
</script>
Your PHP looks oke, after succes you need to echo the path of the image. The 'data' var in success would be the path that you echo'd you now only need to replace the old image using jQuery. I'm not sure if you can do that only with .HTML() but i think this would work.
Related
I am building file upload using php and jquery, I made it without a submit button. But everything is working fine but only there is an error it shows me undefined index message.
This is my html code:
<div id='show'></div>
<form action='demo.php' method='POST' enctype='multipart/form-data'>
<input type='file' id='file' name='file'>
</form>
This is my jquery code:
$(document).ready(function(){
$('#file').change(function(){
var name = $('#file').attr('name');
$.ajax({
url: 'demo.php',
type: 'POST',
data: {'file':name},
beforeSend: function(){
$('#show').html('Loading...');
},
success: function(data){
$('#show').html(data);
}
});
return false
});
});
This is my php code:
if(isset($_FILES['file'])){
$file = $_FILES['file'];
// File properties
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
//Extension
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('jpg', 'png');
if(in_array($file_ext, $allowed)){
if($file_error === 0){
if($file_size <= 2097152){
$new_file = uniqid('', true) . '.' . $file_ext;
$file_destination = 'uploads/' . $new_file;
if(move_uploaded_file($file_tmp, $file_destination)){
echo $file_destination;
}
}
}
}
}
I don't know what is the error and why it's coming.
You are not sending data to $_FILES, but to $_POST actually.
Note the data parameter in your $.ajax() call: data: {'file':name}
Instead of using the jQuery .ajax function, just have the form "submit
$(document).ready(function(){
$('#file').change(function(){
$('form').submit();
return false
});
});
add following right after
// Disable errors completely
error_reporting(0);
This will help you to remove/ hide all error messages including fatal errors.
Alternatively you can use
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
You can also view PHP Official documents for alternative options.
Viewing your problem in detail seems more identical like you are trying to upload file via Ajax. Please read a sample about this scenario on Simple File Upload Using jQuery.
I'm trying to upload files using php and I am copying and renaming files from other instances that are actually working (uploading pics). But for some reason the form is not passing (POST) any file that is NOT an image :-/
So, in resume, I am getting this (Google) 'request payload' for an image file:
------WebKitFormBoundaryrHOYostaC2KnUDlD
Content-Disposition: form-data; name="uploaded_file[]"; filename="image.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryrHOYostaC2KnUDlD--
But this for txt or pdf files:
------WebKitFormBoundaryc1RJOtSOpYKAZiBz--
Here is the form and script (functions are to avoid the user to click 'Submit', those work good):
echo '
<script language="JavaScript" type="text/javascript">
function HandleBrowseClick()
{
var fileinput = document.getElementById("uploaded_file");
fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("uploaded_file");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;
}
</script>';
echo '
<form enctype="multipart/form-data" target="_blank" name="send_file" id="send_file" method="post" action="file_upload.php">
<input type="file" class="hide button" id="uploaded_file" name="uploaded_file" onChange="Handlechange();"/>
<button type="submit" id="btn">Upload!</button>
</form>';
echo '
<div onclick="HandleBrowseClick();" id="fakeBrowse" >Load a file</div>
<input type="text" id="filename" size="50" readonly="true" />
';
So, since it's not passing anything, in my file_upload.php I get the "ERROR: Please browse for a file before clicking the upload button." or "Invalid argument supplied for foreach()" (if I expect an array) error.
I tried using application/x-www-form-urlencoded allowing the same result. Now for those who get mad if there is no question marks: Why the form works fine with images but not so with other kind of files? What am I dong wrong?
Here is the first few lines of file_upload.php (I don't think it's necessary but you never know):
$target = "../files/temp/";
foreach ($_FILES["uploaded_file"]["error"] as $key => $error) {
if ($error != UPLOAD_ERR_OK) { echo "error"; die;}
$fileName = $target . $_FILES["uploaded_file"]["name"][$key]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"][$key]; // File in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"][$key]; // The type of file it is
$fileSize = $_FILES["uploaded_file"]["size"][$key]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"][$key]; // 0 for false... and 1 for true last $key!!!
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename
$fileName = strtolower($fileName);
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occurred while processing the file. Try again.";
exit();
}
Finally, some more js:
if (window.FormData) {
formdata = new FormData();
document.getElementById("btn").style.display = "none";
}
input.addEventListener("change", function (evt) {
document.getElementById("response").innerHTML = "Loading . . ."
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if (formdata) {
formdata.append("uploaded_file[]", file);
}
}
}
if (formdata) {
$.ajax({
url: "file_upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false
}).done(function (res) {
document.getElementById("response").innerHTML = res;
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
});
}
}, false);
where changing contentType doesn't make any diference
THANKS!!!
You have to define the MIME types for your files. For example
.pdf application/pdf
.doc application/msword
Okay, my bad. The js file has an image filter. It started working right away after I removed it.
I have a script working to upload images without refreshing the page using jquery.form.js
Below is the PHP file that it kicks off the processes the file and when finished PHP creates an tag to show the image.
I now need a method to let JQUERY know the PHP file processing has completed. Is there a good way to connect these two?
I thought I could write something hidden to the page and have JQUERY look for this but I'm not sure if this is a B-Grade solution.
Any ideas? I can explain better if needed. thx
<?php
$type = $_POST['mimetype'];
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
foreach($_FILES as $file) {
$filename = $file['name'];
$filesize = $file['size'];
$filetmp = $file['tmp_name'];
}
// Script Variables
$errors=0;
$notAllowedFileType=0;
$exceededMaxFileSize=0;
$maxsize='10485760'; // 10MB Maximum Upload
$folder = 'images/';
$configWidth = 500;
$newFileName = 'success_story'.time().'.jpg';
// Process if No Errors
if(!$errors) {
// Variables
$uploadedFile = $filetmp;
$filename = basename( $filename);
$extension = strtolower(getExtension($filename));
// Convert the Specific Type of File into an Image
if($extension=='jpg' || $extension=='jpeg' ) {
$uploadedfile = $fullfilepath;
$src = imagecreatefromjpeg($uploadedFile);
}elseif($extension=='png') {
$uploadedfile = $fullfilepath;
$src = imagecreatefrompng($uploadedFile);
}else{
$uploadedfile = $fullfilepath;
$src = imagecreatefromgif($uploadedFile);
}
// Configure Width & Height
list($origWidth, $origHeight) = getimagesize($uploadedFile);
$configHeight = ($origHeight/$origWidth)* $configWidth;
// Create Empty File
$tmp = imagecreatetruecolor($configWidth, $configHeight);
imagecopyresampled($tmp, $src, 0,0,0,0,$configWidth,$configHeight,$origWidth,$origHeight);
imagejpeg($tmp, $_SERVER['DOCUMENT_ROOT'].$folder.$newFileName,90);
echo "<img src=".$folder.$newFileName." id=\"cropMeNowImage\">";
}
// Get Extension from Uploaded File
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) {return "";}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script>
(function() {
$(document).on('change','img#cropMeNowImage', function() {
alert('Ready to Crop');
});
})();
</script>
You need to use a callback function. Something like:
$(document).on('change','img#cropMeNowImage', function() {
$.post(url, {
vars_to_server : vars
}, function(process_done){
if (process_done)
alert("ready");
})
});
php must echo something recognizable by jquery in the var process_done
Instead:
echo "<img src=".$folder.$newFileName." id=\"cropMeNowImage\">";
you can echo 1 for success
This is the idea. It's totally possible. Specially for the common task of upload files via AJAX...
I recommend you: 5 Ways to Make Ajax Calls with jQuery
Take a look to http://github.com/valums/file-uploader I always use it to upload files.
i have a script that uploads an image into a folder instead of saving it as a blob..
<?php
mysql_connect('localhost','root','')or die(mysql_error());
mysql_select_db('db_tourism')or die(mysql_error());
//$newname='baro.jpg';
//dir:[../../]
$uploaddir = '../../images/municipality/';
$cc=$uploaddir.$fileName;
$fileName = $_FILES['uploadfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$ext = end(explode('.', $fileName));
$newname=$fileName;//.'.'.$ext;
$file = $uploaddir .$newname; //basename($_FILES['uploadfile']['name']);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
// echo "<script>alert('success:$fileName');</script>";
mysql_query("INSERT INTO `_temp-image` ( `id` , `File_name` , `path` )
VALUES (
NULL , '$fileName', '$file'
);");
echo "success";
}
else {
echo "error";
}
?>
and here is the jquery
var btnUpload=$('#uploada');
//var btnUploadTxt=$('#uploada').attr('value');
var status=$('#status');
new AjaxUpload(btnUpload, {
action: 'upload-file.php',
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
btnUpload.val('Only JPG, PNG or GIF files are allowed');
return false;
}
btnUpload.val('Uploading...');
},
onComplete: function(file, response){
//On completion clear the status
btnUpload.val('Upload Picture');
//Add uploaded file to list
if(response==="success"){
$('<li class="uplod" uid="_temp-image" title="click to remove ['+file+']" id="'+file+' "><span id=" '+file+' " style="font- family:calibri;font-size:10px;" >'+file+' [UPLOADED]</span></li>').appendTo('#uploaded');/ *.html('<img src="../uploaded_image/'+file+'" alt="" />'+file)*///.addClass('success');
} else{
$('<li></li>').appendTo('#uploaded').text(fi le).addClass('error');
}
}
});
it works fine i can add and delete picture... BUT my problem is handling DUPLICATE files... how to error trap if that kind of image is already uploaded??
Generate CRC checksum, MD5 or other hash type for image binary data and store that hash in database.
After upload - check new image checksum/hash and compare it with that stored in database.
Use md5_file function.
$md5hash = md5_file(string $filename);
Here is more: http://www.php.net/manual/en/function.md5-file.php
I want to upload and crop an image via ajax.
Please suggest how I can do this.
To upload an image you will need javascript process handling the upload , there are plenty plugins to do it if you are using jquery library.
To handle uploading process you will need php script. You are sending request to php script from ajax and it does the upload .
To crop image you need a crop tool or crop script here is a cool one http://www.webresourcesdepot.com/jquery-image-crop-plugin-jcrop/
After you handled cropped image you need to execute uploading process (php) by jquery uploader plugin , or another jquery or javascript ajax code.
Here is the code Jquery + PHP [Cake PHP]
View file upload.ctp
<script type="text/javascript" src="http://demos.9lessons.info/ajaximageupload/scripts/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#photoimg').on('change', function(){
$("#preview").html('');
$("#preview").html('<img src="/images/ajax-loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm({target: '#preview',success: showResponse}).submit();
});
});
</script>
<form id="imageform" method="post" enctype="multipart/form-data" action='/media/upload'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'></div>
create a function with name upload in Media controller
function upload(){
$this->layout = '';
$session_id='1'; // User session id
$path = "images/media/images/original/";
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
//pr($_FILES);die;
//if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)){
if($size<(1024*1024)) { // Image size max 1 MB
$txt=str_replace(" ","_",$txt);
$actual_image_name = $txt."_".time().".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
App::import('Vendor', 'resize');
if(move_uploaded_file($tmp, $path.$actual_image_name)) { //Code for image resize
//mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
// save this to DB into Temp Selection table set USer wise and Capsule or individual Board wise
echo "<img src='/images/media/images/".$actual_image_name."' class='preview'><br/><a href='javascript:void(0);' id='upload_submit'>Submit</a>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file fo`enter code here`rmat..";
}
else
echo "Please select image..!";
exit;
}
}