In my situation, I have images upload form with resize method but it failed.
I have below code but does not know why where is the problem. Do you have any ideas? There is function in controller check_base64_image($base64) in which the code said there is null value. I am using PHP of codeingiter
//----font end php html code with javascript------------//
<input id="image1" name="image1" class="file" type="file" accept="image/*">
<button type="submit" class="btn btn-primary btn-tw" onclick="setup(); return false;">Submit</button>
<script>
$("#image1").fileinput({
'showPreview' : true,
'allowedFileExtensions' : ['jpg', 'png','gif'],
'showUpload' : false,
'maxFileCount':1,
'maxFileSize': 8000,
});
$('#image1').on('fileclear', function(event) {
img1 = null;
});
$('#image1').on('fileloaded', function(event, file, previewId, index, reader) {
img1 = file;
$("#uploadImgError").html('');
});
function getResizeImage(pic, callback)
{
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
// Create an image
//-----------------------------Image-------------------------
var img = document.createElement("img");
img.src = e.target.result;
var canvas = document.createElement("canvas");
//var canvas = $("<canvas>", {"id":"testing"})[0];
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 800;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
//document.getElementById('image').src = dataurl;
callback(dataurl);
}
reader.readAsDataURL(pic);
}
function isEmptyUploadFile(callback)
{
if(img1 == null && img2 == null && img3 == null && img4 == null && img5 == null)
callback(true);
else
callback(false);
}
function setForm(callback)
{
setImg1(function(data1)
{
if(data1 == true)
{
$('.progress-bar').css('width', 100+'%').attr('aria-valuenow', 100);
callback(true);
}
});
}
function setImg1(callback)
{
if(img1 != null)
{
getResizeImage(img1,function(tempPic)
{
document.getElementById('img1').value = tempPic;
getResizeThumbnailImage(img1,function(tempTPic)
{
document.getElementById('timg1').value = tempTPic;
$('.progress-bar').css('width', 20+'%').attr('aria-valuenow', 20);
callback(true);
});
});
}else{
$('.progress-bar').css('width', 20+'%').attr('aria-valuenow', 20);
callback(true);
}
}
function setup()
{
var myform = document.getElementById("newPost");
//console.log(myform.checkValidity());
if(!myform.checkValidity())
{
document.getElementById("validate").click();
return false;
}
isEmptyUploadFile(function(r)
{
var up1 = document.getElementById('image1').value;
var up2 = document.getElementById('image2').value;
var up3 = document.getElementById('image3').value;
var up4 = document.getElementById('image4').value;
var up5 = document.getElementById('image5').value;
if(r == true || (up1 == "" && up2 == "" && up3 == "" && up4 == "" && up5 == "") )
{
$("#uploadImgError").html('<em><span style="color:red"> <i class="icon-cancel-1 fa"></i> Please Upload at least one image!</span></em>');
//var loc = document.getElementById('uploadImgError'); //Getting Y of target element
//window.scrollTo(0, loc);
location.href = "#uploadImgError"; //Go to the target element.
return false;
}
else if(r == false)
{
$('#pleaseWaitDialog').modal('show');
setForm(function(data)
{
console.log(data);
if(data == true)
{
document.getElementById("newPost").submit();
}
return data;
});
}
});
}
</script>
// ------- controller ---------------------------//
$image1 = $this->input->post('img1');
$timage1 = $this->input->post('timg1');
$imgPath = '';
$timgPath = '';
$date=date_create();
if (isset($image1)) {
$currentTimeStamp = date_timestamp_get($date);
$imgPath = $upload_dir . '/['.$currentTimeStamp.']['.$userName.'].png';
$result = $this->uploadImg($image1, false, $imgPath);
}
if (isset($timage1)) {
$currentTimeStamp = date_timestamp_get($date);
$timgPath = $upload_dir . '/[T]['.$currentTimeStamp.']['.$userName.'].png';
$result = $this->uploadImg($timage1, true, $timgPath);
}
function uploadImg($input, $isThumbnail, $file)
{
if($input == null || $input == "")
{
return false;
}
$stringVal = $input;
$value = str_replace('data:image/png;base64,', '', $stringVal);
if ($this->check_base64_image($value) == false) {
return false;
}
$actualFile = base64_decode($value);
$img = imagecreatefromstring($actualFile);
$imgSize = getimagesize('data://application/octet-stream;base64,'.base64_encode($actualFile));
if ($img == false) {
return false;
}else
{
/*** maximum filesize allowed in bytes ***/
$max_file_length = 100000;
$maxFilesAllowed = 10;
log_message('debug', 'PRE UPLOADING!!!!!!!!');
if (isset($img)){
log_message('debug', 'UPLOADING!!!!!!!!');
// check the file is less than the maximum file size
if($imgSize['0'] > $max_file_length || $imgSize['1'] > $max_file_length)
{
log_message('debug', 'size!!!!!!!!'.print_r($imgSize));
$messages = "File size exceeds $max_file_size limit";
return false;
}else if (file_exists($file)) {
return false;
}else
{
return true;
}
}
function check_base64_image($base64) {
$img = imagecreatefromstring(base64_decode($base64));
// this code said null value.
if (!$img) {
return false;
}
imagepng($img, 'tmp.png');
$info = getimagesize('tmp.png');
unlink('tmp.png');
if ($info[0] > 0 && $info[1] > 0 && $info['mime']) {
return true;
}
return false;
}
//-------------------end --------//
Related
I am trying to upload larger image file 100MB to php server.
It looks like a whole file uploaded (got status 200), but on server side there is wrong file size, lost few bytes, and it is not displayed as image in web browser.
How to fix?
Here is htmlp/javascript :
var file = document.getElementById("selectedfile").files[0];
var reader = new FileReader();
//reader.readAsBinaryString(file);
reader.readAsDataURL(file);
reader.onloadend = function(evt){
xhr = new XMLHttpRequest();
xhr.open("POST", "uprx.php?filename="+document.getElementById("selectedfile").files[0].name, true);
XMLHttpRequest.prototype.mySendAsBinary = function(text){
var data = new ArrayBuffer(text.length);
var ui8a = new Uint8Array(data, 0);
for (var i=0; i<text.length; i++) {
ui8a[i] = (text.charCodeAt(i)&0xff);
}
if (typeof window.Blob == "function") {
var blob = new Blob([data]);
}
else {
var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
bb.append(data);
var blob = bb.getBlob();
}
this.send(blob);
}
var eventSource = xhr.upload || xhr;
eventSource.addEventListener("progress", function(e) {
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = Math.round((position/total)*100);
});
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
}
else {
// process error
}
}
};
xhr.mySendAsBinary(evt.target.result);
};
Here is php server :
$inputHandler = fopen("php://input", "r");
$fileHandler = fopen($_GET["filename"], "w");
while(true) {
$buffer = fgets($inputHandler, 4096);
if (strlen($buffer) == 0) {
fclose($inputHandler);
fclose($fileHandler);
return true;
}
$base64Image = trim($buffer);
$base64Image = str_replace('data:image/png;base64,', '', $base64Image);
$base64Image = str_replace('data:image/jpg;base64,', '', $base64Image);
$base64Image = str_replace('data:image/jpeg;base64,', '', $base64Image);
$base64Image = str_replace('data:image/gif;base64,', '', $base64Image);
//$base64Image = str_replace(' ', '+', $base64Image);
$imageData = base64_decode($base64Image);
fwrite($fileHandler, $imageData);
}
I am trying to upload multiple images to php server, But for some reason it is using first image name for all the uploaded images, saving to same image name. I want it to save to their filename in the source folder. Like Banner1.jpg,Banner2.jpg and Banner3.jpg should be saved. But it is saving first image thrice.
$filesCount = count($_FILES['photos']['name']);
$success = 0;
for($i = 0; $i < $filesCount; $i++)
{
$uploadedfile = $_FILES['photos']['tmp_name'][$i];
if($uploadedfile)
{
$filename = stripcslashes($_FILES['photos']['name'][$i]);
$extension = $this->getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$change='<div class="msgdiv">Unknown Image extension </div>';
}
else
{
$size = filesize($_FILES['photos']['tmp_name'][$i]);
}
if($size > MAX_SIZE*1024)
{
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['photos']['tmp_name'][$i];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['photos']['tmp_name'][$i];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=1024;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=300;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
$filenameee = "server/php/rental/". $_FILES['photos']['name'][$i];
$filenameee1 = "server/php/rental/small/". $_FILES['photos']['name'][$i];
imagejpeg($tmp,$filenameee,100);
imagejpeg($tmp1,$filenameee1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
if(mysql_query("INSERT INTO fc_rental_photos(product_image,product_id) VALUES('$filename','$prd_id')"))
{
$success++;
}
}
Here is the input field i am using to upload images.
<form id="imageform" method="post" enctype="multipart/form-data" action="/path-to-controller-method/">
<input type="file" name="photos[]" id="photoimg" multiple onchange="imageval();">
</form>
IMageVal
function imageval(){ /*Image size validation*/
var fi = document.getElementById('photoimg');
if (fi.files.length > 0) { // FIRST CHECK IF ANY FILE IS SELECTED.
for (var i = 0; i <= fi.files.length - 1; i++) {
var fileName, fileExtension, fileSize, fileType, dateModified;
fileName = fi.files.item(i).name;
fileExtension = fileName.replace(/^.*\./, '');
if (fileExtension == 'png' || fileExtension == 'jpg' || fileExtension == 'jpeg') {
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(fi.files.item(i));
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
//Validate the File Height and Width.
image.onload = function () {
var height = this.height;
var width = this.width;
if (width < 1450 || height < 500) {
alert("Image Height and Width should be Above 1450 * 500 px.");
return false;
}
<?php if($aws == 'Yes') echo "uploadImage_aws();";else echo "uploadImage();";?>
};
}
}
else
{
alert("Photo only allows file types of PNG, JPG, JPEG. ");
}
}
}
}
UploadImage
function uploadImage()
{
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
}
}).submit();
}
You have to check if the data already exists, and if not to rename it.
if(file_exists($new_path)) {
$id = 1;
do {
$new_path = $upload_folder.$filename.'_'.$id.'.'.$extension;
$id++;
} while(file_exists($new_path));
}
For example
$new_path = $upload_folder.$filename.'.'.$extension;
This when I send ajax request to my controller to crop and resize it, instead it resize it but my image turns black. I even tried adding header so that my browser can understands that it is a valid image file format. Where I am missing?
**My ajax call to controller**
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#change-pic').on('click', function(e){
jQuery('#changePic').show();
jQuery('#change-pic').hide();
});
jQuery('#photoimg').on('change', function()
{
jQuery("#preview-avatar-profile").html('');
jQuery("#preview-avatar-profile").html('Uploading....');
jQuery("#cropimage").ajaxForm(
{
target: '#preview-avatar-profile',
success: function() {
jQuery('img#photo').imgAreaSelect({
aspectRatio: '1:1',
onSelectEnd: getSizes,
});
jQuery('#image_name').val(jQuery('#photo').attr('file-name'));
}
}).submit();
});
jQuery('#btn-crop').on('click', function(e){
e.preventDefault();
params = {
//targetUrl: 'profile.php?action=save',
targetUrl: 'http://172.16.0.60/cakephp/users/croppedimage',
//action: 'save',
x_axis: jQuery('#hdn-x1-axis').val(),
y_axis : jQuery('#hdn-y1-axis').val(),
x2_axis: jQuery('#hdn-x2-axis').val(),
y2_axis : jQuery('#hdn-y2-axis').val(),
thumb_width : jQuery('#hdn-thumb-width').val(),
thumb_height:jQuery('#hdn-thumb-height').val()
};
saveCropImage(params);
});
function getSizes(img, obj)
{
var x_axis = obj.x1;
var x2_axis = obj.x2;
var y_axis = obj.y1;
var y2_axis = obj.y2;
var thumb_width = obj.width;
var thumb_height = obj.height;
if(thumb_width > 0)
{
jQuery('#hdn-x1-axis').val(x_axis);
jQuery('#hdn-y1-axis').val(y_axis);
jQuery('#hdn-x2-axis').val(x2_axis);
jQuery('#hdn-y2-axis').val(y2_axis);
jQuery('#hdn-thumb-width').val(thumb_width);
jQuery('#hdn-thumb-height').val(thumb_height);
}
else
alert("Please select portion..!");
}
function saveCropImage(params) {
jQuery.ajax({
url: params['targetUrl'],
cache: false,
dataType: "html",
data: {
action: params['action'],
id: jQuery('#hdn-profile-id').val(),
t: 'ajax',
w1:params['thumb_width'],
x1:params['x_axis'],
h1:params['thumb_height'],
y1:params['y_axis'],
x2:params['x2_axis'],
y2:params['y2_axis'],
image_name :jQuery('#image_name').val()
},
type: 'Post',
// async:false,
success: function (response) {
jQuery('#changePic').hide();
jQuery('#change-pic').show();
jQuery(".imgareaselect-border1,.imgareaselect-border2,.imgareaselect-border3,.imgareaselect-border4,.imgareaselect-border2,.imgareaselect-outer").css('display', 'none');
jQuery("#avatar-edit-img").attr('src', response);
jQuery("#preview-avatar-profile").html('');
jQuery("#photoimg").val('');
},
error: function (xhr, ajaxOptions, thrownError) {
alert('status Code:' + xhr.status + 'Error Message :' + thrownError);
}
});
}
});
</script>
This is one first when I upload the image and preview it.
public function wall()
{
$post = isset($_POST) ? $_POST: array();
$max_width = "500";
$userId = isset($post['hdn-profile-id']) ? intval($post['hdn-profile-id']) : 0;
// $path = 'http://172.16.0.60/cakephp/webroot/img/tmp';
$path = WWW_ROOT.'img/tmp/' ;
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
$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
{
$actual_image_name = 'avatar' .'_'.$userId .'.'.$ext;
$filePath = $path .'/'.$actual_image_name;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $filePath))
{
// /$this->setPassword($this->request->data['password']);
$width = $this->getWidth($filePath);
$height = $this->getHeight($filePath);
//Scale the image if it is greater than the width set above
if ($width > $max_width)
{
$scale = $max_width/$width;
$uploaded = $this->resizeImage($filePath,$width,$height,$scale);
}
else
{
$scale = 1;
$uploaded = $this->resizeImage($filePath,$width,$height,$scale);
}
/*
echo "<img id='photo' file-name='".$actual_image_name."' class='' src='".'file://'.$filePath.'?'.time()."' class='preview'/>";
*/
$mypath = '/cakephp/img/tmp/'.$actual_image_name;
echo "<img id='photo' file-name='".$actual_image_name."' class='' src='".$mypath."' class='preview'/>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
My Controller code where I use the function imagecopyresampled() but idk where I am going wrong.?
Any solution
public function croppedimage()
{
header('Content-Type: image/png');
$post = isset($_POST) ? $_POST: array();
$userId = isset($post['id']) ? intval($post['id']) : 0;
//$path ='\images\uploads\tmp';
$path = WWW_ROOT.'img/tmp/uploads/' ;
$t_width = 300; // Maximum thumbnail width
$t_height = 300; // Maximum thumbnail height
if(isset($_POST['t']) and $_POST['t'] == "ajax")
{
extract($_POST);
//$img = get_user_meta($userId, 'user_avatar', true);
//$filePath = $path .'/'.$actual_image_name;
$imagePath = $path.$_POST['image_name'];
$ratio = ($t_width/$w1);
$nw = ceil($w1 * $ratio);
$nh = ceil($h1 * $ratio);
$nimg = imagecreatetruecolor($nw,$nh);
$im_src = imagecreatefromjpeg($imagePath);
imagecopyresampled($nimg,$im_src,0,0,$x1,$y1,$nw,$nh,$w1,$h1);
imagejpeg($nimg,$imagePath,90);
}
echo $imagePath.'?'.time();;
exit(0);
die();
}
In my situation, I have images upload form with resize method but it failed. I have below code but does not know why where is the problem. Do you have any ideas? I am using PHP of codeingiter. Below is the error that shown. I have hosted the web site on goDaddy.
Request Entity Too Large The requested resource
/index.php/newPost/createNewPost/2/Raymond Chiu/ does not allow request data with GET requests, or the amount of data provided in the request exceeds the capacity limit. Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
//----font end php html code with javascript------------//
<input id="image1" name="image1" class="file" type="file" accept="image/*">
<button type="submit" class="btn btn-primary btn-tw" onclick="setup(); return false;">Submit</button>
<script>
$("#image1").fileinput({
'showPreview' : true,
'allowedFileExtensions' : ['jpg', 'png','gif'],
'showUpload' : false,
'maxFileCount':1,
'maxFileSize': 800000,
});
$('#image1').on('fileclear', function(event) {
img1 = null;
});
$('#image1').on('fileloaded', function(event, file, previewId, index, reader) {
img1 = file;
$("#uploadImgError").html('');
});
function getResizeImage(pic, callback)
{
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
// Create an image
//-----------------------------Image-------------------------
var img = document.createElement("img");
img.src = e.target.result;
var canvas = document.createElement("canvas");
//var canvas = $("<canvas>", {"id":"testing"})[0];
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 800;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
//document.getElementById('image').src = dataurl;
callback(dataurl);
}
reader.readAsDataURL(pic);
}
function isEmptyUploadFile(callback)
{
if(img1 == null && img2 == null && img3 == null && img4 == null && img5 == null)
callback(true);
else
callback(false);
}
function setForm(callback)
{
setImg1(function(data1)
{
if(data1 == true)
{
$('.progress-bar').css('width', 100+'%').attr('aria-valuenow', 100);
callback(true);
}
});
}
function setImg1(callback)
{
if(img1 != null)
{
getResizeImage(img1,function(tempPic)
{
document.getElementById('img1').value = tempPic;
getResizeThumbnailImage(img1,function(tempTPic)
{
document.getElementById('timg1').value = tempTPic;
$('.progress-bar').css('width', 20+'%').attr('aria-valuenow', 20);
callback(true);
});
});
}else{
$('.progress-bar').css('width', 20+'%').attr('aria-valuenow', 20);
callback(true);
}
}
function setup()
{
var myform = document.getElementById("newPost");
//console.log(myform.checkValidity());
if(!myform.checkValidity())
{
document.getElementById("validate").click();
return false;
}
isEmptyUploadFile(function(r)
{
var up1 = document.getElementById('image1').value;
var up2 = document.getElementById('image2').value;
var up3 = document.getElementById('image3').value;
var up4 = document.getElementById('image4').value;
var up5 = document.getElementById('image5').value;
if(r == true || (up1 == "" && up2 == "" && up3 == "" && up4 == "" && up5 == "") )
{
$("#uploadImgError").html('<em><span style="color:red"> <i class="icon-cancel-1 fa"></i> Please Upload at least one image!</span></em>');
//var loc = document.getElementById('uploadImgError'); //Getting Y of target element
//window.scrollTo(0, loc);
location.href = "#uploadImgError"; //Go to the target element.
return false;
}
else if(r == false)
{
$('#pleaseWaitDialog').modal('show');
setForm(function(data)
{
console.log(data);
if(data == true)
{
document.getElementById("newPost").submit();
}
return data;
});
}
});
}
</script>
// ------- controller ---------------------------//
$image1 = $this->input->post('img1');
$timage1 = $this->input->post('timg1');
$imgPath = '';
$timgPath = '';
$date=date_create();
if (isset($image1)) {
$currentTimeStamp = date_timestamp_get($date);
$imgPath = $upload_dir . '/['.$currentTimeStamp.']['.$userName.'].png';
$result = $this->uploadImg($image1, false, $imgPath);
}
if (isset($timage1)) {
$currentTimeStamp = date_timestamp_get($date);
$timgPath = $upload_dir . '/[T]['.$currentTimeStamp.']['.$userName.'].png';
$result = $this->uploadImg($timage1, true, $timgPath);
}
function uploadImg($input, $isThumbnail, $file)
{
if($input == null || $input == "")
{
return false;
}
$stringVal = $input;
$value = str_replace('data:image/png;base64,', '', $stringVal);
if ($this->check_base64_image($value) == false) {
return false;
}
$actualFile = base64_decode($value);
$img = imagecreatefromstring($actualFile);
$imgSize = getimagesize('data://application/octet-stream;base64,'.base64_encode($actualFile));
if ($img == false) {
return false;
}else
{
/*** maximum filesize allowed in bytes ***/
$max_file_length = 100000;
$maxFilesAllowed = 10;
log_message('debug', 'PRE UPLOADING!!!!!!!!');
if (isset($img)){
log_message('debug', 'UPLOADING!!!!!!!!');
// check the file is less than the maximum file size
if($imgSize['0'] > $max_file_length || $imgSize['1'] > $max_file_length)
{
log_message('debug', 'size!!!!!!!!'.print_r($imgSize));
$messages = "File size exceeds $max_file_size limit";
return false;
}else if (file_exists($file)) {
return false;
}else
{
return true;
}
}
function check_base64_image($base64) {
$img = imagecreatefromstring(base64_decode($base64));
// this code said null value.
if (!$img) {
return false;
}
imagepng($img, 'tmp.png');
$info = getimagesize('tmp.png');
unlink('tmp.png');
if ($info[0] > 0 && $info[1] > 0 && $info['mime']) {
return true;
}
return false;
}
//-------------------end --------//
You have to configure your server to accept Large Files.
Also you're using GET.Use Post instead.
See So why should we use POST instead of GET
I may find out the reasons. After I am using native session in PHP from codeigniter session, I find that when I upload small images which will corrupt and cannot see picture. The image file that uploaded after resize in client side with above code.
Should it be reason??
Been working on this annoying son of a gun for 3 days. Hoping someone will be able to offer some assistance. Basically I'm using http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/ to allow multiple file uploads along side with a regular file upload input. The first part of this code is the copying of the original image that was uploaded. That works fine for both. The second part is for thumbnails and it won't work when using the drag-drop script, however it works perfectly using the standard upload. I'm assuming my problem isn't with this code, but I'm including it just to show you. I'll also include almost all the other code in case you find it pertinent and helpful in diagnosing.
// copying original image to new location with new name
$prev = file_get_contents($pic['tmp_name']);
$new = fopen($file, "w");
fwrite($new, $prev);
fclose($new);
//create image for thumbnail
switch(strtolower($pic['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($pic['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($pic['tmp_name']);
imagealphablending($image, true); // setting alpha blending on
imagesavealpha($image, true);
break;
case 'image/gif':
$image = imagecreatefromgif($pic['tmp_name']);
break;
default:
exit('Unsupported type: '.$pic['type']);
}
// Target dimensions
$max_width = 150;
$max_height = 150;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
// Catch the imagedata
ob_start();
//create image for thumbnail
switch(strtolower($pic['type']))
{
case 'image/jpeg':
imagejpeg($new, $_SERVER['DOCUMENT_ROOT']."/".$thumbnail, 90);
break;
case 'image/png';
imagepng($new, $_SERVER['DOCUMENT_ROOT']."/".$thumbnail, 9);
break;
case 'image/gif':
imagegif($new, $_SERVER['DOCUMENT_ROOT']."/".$thumbnail, 9);
break;
default:
exit('Unsupported type: '.$pic['type']);
}
chmod($_SERVER['DOCUMENT_ROOT']."/".$thumbnail,0755);
$data = ob_get_clean();
// Destroy resources
imagedestroy($image);
imagedestroy($new);
The HTML
<h1>Upload Image(s)</h1>
<form action='ajax/post_file.php' method='post' enctype="multipart/form-data">
<input type='file' name='file'><input type='hidden' name='drag_drop' value='yes'><input type='submit' value='go'>
</form>
<!-- Our CSS stylesheet file -->
<link rel="stylesheet" href="ajax/drag_drop_uploads/css/styles.css" />
<div id="dropbox" style='height: 400px; overflow: auto;'>
<span class="message">Drop images here to upload. <br /><i>(they will be automatically uploaded to your account)</i></span>
</div>
The JQuery plugin that handles the drag-drop upload
(function(jQuery){
jQuery.event.props.push("dataTransfer");
var opts = {},
default_opts = {
url: '',
refresh: 1000,
paramname: 'userfile',
maxfiles: 25,
maxfilesize: 5, // MBs
data: {},
drop: empty,
dragEnter: empty,
dragOver: empty,
dragLeave: empty,
docEnter: empty,
docOver: empty,
docLeave: empty,
beforeEach: empty,
afterAll: empty,
rename: empty,
error: function(err, file, i){alert(err);},
uploadStarted: empty,
uploadFinished: empty,
progressUpdated: empty,
speedUpdated: empty
},
errors = ["BrowserNotSupported", "TooManyFiles", "FileTooLarge"],
doc_leave_timer,
stop_loop = false,
files_count = 0,
files;
jQuery.fn.filedrop = function(options) {
opts = jQuery.extend( {}, default_opts, options );
this.bind('drop', drop).bind('dragenter', dragEnter).bind('dragover', dragOver).bind('dragleave', dragLeave);
jQuery(document).bind('drop', docDrop).bind('dragenter', docEnter).bind('dragover', docOver).bind('dragleave', docLeave);
};
function drop(e) {
opts.drop(e);
files = e.dataTransfer.files;
if (files === null || files === undefined) {
opts.error(errors[0]);
return false;
}
files_count = files.length;
upload();
e.preventDefault();
return false;
}
function getBuilder(filename, filedata, boundary) {
var dashdash = '--',
crlf = '\r\n',
builder = '';
jQuery.each(opts.data, function(i, val) {
if (typeof val === 'function') val = val();
builder += dashdash;
builder += boundary;
builder += crlf;
builder += 'Content-Disposition: form-data; name="'+i+'"';
builder += crlf;
builder += crlf;
builder += val;
builder += crlf;
});
builder += dashdash;
builder += boundary;
builder += crlf;
builder += 'Content-Disposition: form-data; name="'+opts.paramname+'"';
builder += '; filename="' + filename + '"';
builder += crlf;
builder += 'Content-Type: application/octet-stream';
builder += crlf;
builder += crlf;
builder += filedata;
builder += crlf;
builder += dashdash;
builder += boundary;
builder += dashdash;
builder += crlf;
return builder;
}
function progress(e) {
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
if (this.currentProgress != percentage) {
this.currentProgress = percentage;
opts.progressUpdated(this.index, this.file, this.currentProgress);
var elapsed = new Date().getTime();
var diffTime = elapsed - this.currentStart;
if (diffTime >= opts.refresh) {
var diffData = e.loaded - this.startData;
var speed = diffData / diffTime; // KB per second
opts.speedUpdated(this.index, this.file, speed);
this.startData = e.loaded;
this.currentStart = elapsed;
}
}
}
}
function upload() {
stop_loop = false;
if (!files) {
opts.error(errors[0]);
return false;
}
var filesDone = 0,
filesRejected = 0;
if (files_count > opts.maxfiles) {
opts.error(errors[1]);
return false;
}
for (var i=0; i<files_count; i++) {
if (stop_loop) return false;
try {
if (beforeEach(files[i]) != false) {
if (i === files_count) return;
var reader = new FileReader(),
max_file_size = 1048576 * opts.maxfilesize;
reader.index = i;
if (files[i].size > max_file_size) {
opts.error(errors[2], files[i], i);
filesRejected++;
continue;
}
reader.onloadend = send;
reader.readAsBinaryString(files[i]);
} else {
filesRejected++;
}
} catch(err) {
opts.error(errors[0]);
return false;
}
}
function send(e) {
// Sometimes the index is not attached to the
// event object. Find it by size. Hack for sure.
if (e.target.index == undefined) {
e.target.index = getIndexBySize(e.total);
}
var xhr = new XMLHttpRequest(),
upload = xhr.upload,
file = files[e.target.index],
index = e.target.index,
start_time = new Date().getTime(),
boundary = '------multipartformboundary' + (new Date).getTime(),
builder;
newName = rename(file.name);
if (typeof newName === "string") {
builder = getBuilder(newName, e.target.result, boundary);
} else {
builder = getBuilder(file.name, e.target.result, boundary);
}
upload.index = index;
upload.file = file;
upload.downloadStartTime = start_time;
upload.currentStart = start_time;
upload.currentProgress = 0;
upload.startData = 0;
upload.addEventListener("progress", progress, false);
xhr.open("POST", opts.url, true);
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary='
+ boundary);
xhr.sendAsBinary(builder);
opts.uploadStarted(index, file, files_count);
xhr.onload = function() {
if (xhr.responseText) {
var now = new Date().getTime(),
timeDiff = now - start_time,
result = opts.uploadFinished(index, file, jQuery.parseJSON(xhr.responseText), timeDiff);
filesDone++;
if (filesDone == files_count - filesRejected) {
afterAll();
}
if (result === false) stop_loop = true;
}
};
}
}
function getIndexBySize(size) {
for (var i=0; i < files_count; i++) {
if (files[i].size == size) {
return i;
}
}
return undefined;
}
function rename(name) {
return opts.rename(name);
}
function beforeEach(file) {
return opts.beforeEach(file);
}
function afterAll() {
return opts.afterAll();
}
function dragEnter(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.dragEnter(e);
}
function dragOver(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docOver(e);
opts.dragOver(e);
}
function dragLeave(e) {
clearTimeout(doc_leave_timer);
opts.dragLeave(e);
e.stopPropagation();
}
function docDrop(e) {
e.preventDefault();
opts.docLeave(e);
return false;
}
function docEnter(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docEnter(e);
return false;
}
function docOver(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docOver(e);
return false;
}
function docLeave(e) {
doc_leave_timer = setTimeout(function(){
opts.docLeave(e);
}, 200);
}
function empty(){}
try {
if (XMLHttpRequest.prototype.sendAsBinary) return;
XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
this.send(ui8a.buffer);
}
} catch(e) {}
})(jQuery);
The JQuery that is called to and from the plugin
jQuery(function(){
var dropbox = jQuery('#dropbox'),
message = jQuery('.message', dropbox);
dropbox.filedrop({
// The name of the jQuery_FILES entry:
paramname:'file',
maxfiles: 25,
maxfilesize: 5,
url: 'ajax/post_file.php',
uploadFinished:function(i,file,response){
jQuery.data(file).addClass('done');
// response is the JSON object that post_file.php returns
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files! Please select 5 at most! (configurable)');
break;
case 'FileTooLarge':
alert(file.name+' is too large! Please upload files up to 2mb (configurable).');
break;
default:
break;
}
},
// Called before each upload is started
beforeEach: function(file){
if(!file.type.match(/^image\//)){
alert('Only images are allowed!');
// Returning false will cause the
// file to be rejected
return false;
}
},
uploadStarted:function(i, file, len){
createImage(file);
},
progressUpdated: function(i, file, progress) {
jQuery.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">'+
'<span class="imageHolder">'+
'<img />'+
'<span class="uploaded"></span>'+
'</span>'+
'<div class="progressHolder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
function createImage(file){
var preview = jQuery(template),
image = jQuery('img', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function(e){
// e.target.result holds the DataURL which
// can be used as a source of the image:
image.attr('src',e.target.result);
};
// Reading the file as a DataURL. When finished,
// this will trigger the onload function above:
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
// Associating a preview container
// with the file, using jQuery's jQuery.data():
jQuery.data(file,preview);
}
function showMessage(msg){
message.html(msg);
}
});
The sample PHP they gave me
$demo_mode = false;
$upload_dir = 'ajax/uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'],
$pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
As discussed in the OPs comments;
It seems the file upload example isn't correctly populating the filetype resulting in hitting the switch's default block (an exit)
Incidentally, you may want to swap this to throwing an exception so you'll see something useful in the logs in future