Upload on server image html2canvas - php

I have this js :
$.ajax({
url: 'ajaxfile.php',
type: 'POST',
data: {
image: base64URL
},
success: function(data){
console.log(data);
$.notify("info", "Upload successfully");
},
error: function () {
$.notify("Error on image upload");
}
});
PHP code :
<?php
$image = $_POST['image'];
$location = "src/upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
$filename = "screenshot_".uniqid().'.png';
$file = $location . $filename;
file_put_contents($file, $image_base64);
return [
'status' => true
]
?>
The call is done (I saw in browser console) but on console.log I have the code php returned. Seems that nothing happen, the code php is not implemented. Have you an idea ? Thx in advance and sorry for my english
I put an image with the error

file_put_contents() returns false on failure, so you could assign it to a variable and use that to determine your status like so:
<?php
$image = $_POST['image'];
$location = "src/upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
$filename = "screenshot_".uniqid().'.png';
$file = $location . $filename;
$imageData = file_put_contents($file, $image_base64);
if ($imageData !== false) {
echo "success";
} else {
http_response_code(500);
die();
}
?>

Related

How to upload base64 image on codeigniter

I am working with php,I am getting Base64 image in api,And i want to save/store
into database and want to upload image into server,how can i do this ?
I tried with following code but getting following error
"failed to open content, Http writer doest not support writetable connections"
function imageupload()
{
$data = json_decode(file_get_contents("php://input"), TRUE);
$files=file_get_contents($_FILES["file"]["tmp_name"]);
$image = base64_decode($files);
$image_name = md5(uniqid(rand(), true));
$filename = $image_name . '.' . 'png';
$path = base_url().'upload/blog/';
file_put_contents($path . $filename, $image);
}
Remove base_url() from path.
OR
Check this out
jQuery :
$(document).on('click', '#upload', function () {
let form_data = new FormData();
let data_url = document.getElementById('my_image').toDataURL('image/png');
data_url = data_url.replace(/^data:image\/(png|jpg|jpeg);base64,/, '');
form_data.append('uploaded_image', data_url);
$.ajax({
url: 'upload-avatar',
method: 'post',
data: form_data,
dataType: 'json',
contentType: false,
async: true,
processData: false,
cache: false
});
});
PHP :
$img = $this->request->getPost('uploaded_image'); // for ci4
$img = $this->input->post('uploaded_image'); // for ci3
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$file_data = base64_decode($img);
file_put_contents(/* my_path and my_file_name */, $file_data);

File upload URL

I am trying to upload a canvas image to my server using AJAX, the AJAX is working fine, however when I give the server the URL it converts it and adds backslash in at every folder in the URL, and I cant see how. I need it to stop adding these backslashes into the string.
if(isset($_POST['saveCanvas']) && $_POST['saveCanvas'] == "1"){
$img = $_POST['canvasURL'];
$img = str_replace('data:image/png;base64','',$img);
$img = str_replace(' ', '+',$img);
$data = base64_decode($img);
$file = "https://example.com/wp-content/plugins/my-plugin/images" . uniqid() . '.png';
$success = file_put_contents($file, $data);
$return = [];
$return['success'] = 1;
$return['message'] = 'Image Uploaded! ' . $file;
echo json_encode($return);
}
This is what I want the output to look like https://example.com/wp-content/plugins/my-plugin/images and this is the current output https:\/\/example.com\/wp-content\/plugins\/my-plugin\/images5f7d97548917d.png
If I am not mistaken, this happens because you are JSON encoding your return array. Did you try to just returning $file upon success?
Based on your current issue I would suggest you do this on your php.
if(isset($_POST['saveCanvas']) && $_POST['saveCanvas'] == "1"){
$img = $_POST['canvasURL'];
$img = str_replace('data:image/png;base64','',$img);
$img = str_replace(' ', '+',$img);
$data = base64_decode($img);
$file = "https://example.com/wp-content/plugins/my-plugin/images" . uniqid() . '.png';
echo file_put_contents($file, $data) ? $file : 0;
}
This will check if the file has been uploaded and return a file name or the integer 0.
When the response reaches your ajax, the ajax will check the response.
if its 0, it will be counted as false so you can do.
if(response){
//success code
}else{
//fail code
}
For example
alert(response ? 'Image Uploaded! '+ response : 'Failed to upload');

posting of dataurl to php

ajax.open("POST", "upload.php", true);
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//ajax.setRequestHeader("Content-Type", "image/png",1);
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
alert(ajax.responseText);
}
}
ajax.send("imgData=" + canvasData);
}
This is the xmlhttprequest that sends the data to upload.php which says that it is unable to save the file. However the php page saves the file with 0B.
<?php
// Requires php5
define('UPLOAD_DIR', 'images/');
$img = $_POST['canvasData'];
print $img;
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
Above being the php file to which the data gets posted......
If you want to upload file into directory use move_uploaded_file function , but your question unclear , check the following post link

Ajax success function not outputting text sent by Php script

I am uploading multiple files with this PHP script below:
<?php
if(isset($_FILES['uploadfile'])){
$total_files = count($_FILES['uploadfile']['name']);
if( $total_files > 0){
for($i=0; $i<$total_files; $i++) {
$file_name = $_FILES['uploadfile']['name'][$i];
$file_size = $_FILES['uploadfile']['size'][$i];
$file_tmp = $_FILES['uploadfile']['tmp_name'][$i];
$file_type = $_FILES['uploadfile']['type'][$i];
$upload_Path = "storage/".$file_name;
//var_dump($file_size);
//die;
if($file_size > 8000000){
echo ('Total upload size must be less than 8 MB.');
die;
}
if($file_tmp == ""){
echo ('There is no file path.');
die;
}
else{
if(!file_exists($upload_Path)){
move_uploaded_file($file_tmp, $upload_Path);
}
else{
$name = pathinfo($file_name, PATHINFO_FILENAME);
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$new_name = $name.rand().'.'.$ext;
$new_Path = "storage/".$new_name;
move_uploaded_file($file_tmp, $new_Path);
}
}
}
}
die('File uploaded successfully!');
}
?>
but the problem is that whenever an error occurs such as echo ('Total upload size must be less than 8 MB.'); it doesn't get outputed using ajax. But when a successful upload is done it shows File uploaded successfully!.
My AJAX is as follows:
$.ajax({
type:'POST',
url: 'mupld.php',
data: formdata,
processData:false,
contentType:false,
success: function(response){
alert('Success: '+response);
},
error: function(xhr, status, error){
alert('Error: '+status+' '+error);
}
});
On doing a var dump I dont get any output for uploads above 8mb but for below that I get
Success: <pre class='xdebug-var-dump' dir='ltr'><small>int</small> <font color='#4e9a06'>3283515</font>
</pre>
#Jeff Bucket was right, so I edited my answer:
Actually, you should handle those errors in your success callback. The error() callback is reserved for situations where the connection between browser and server just breaks, and the error() parameters expect to handle those kind of situations, for example a typical textStatus error should be 'Not Found' or 'Internal Server Error', but no 'Total upload size must be less than 8 MB.'.
You should return an array with information you can use in the client, and handle that in success(), like:
try{
if(isset($_FILES['uploadfile'])){
$total_files = count($_FILES['uploadfile']['name']);
if( $total_files > 0){
for($i=0; $i<$total_files; $i++) {
$file_name = $_FILES['uploadfile']['name'][$i];
$file_size = $_FILES['uploadfile']['size'][$i];
$file_tmp = $_FILES['uploadfile']['tmp_name'][$i];
$file_type = $_FILES['uploadfile']['type'][$i];
$upload_Path = "storage/".$file_name;
//var_dump($file_size);
//die;
if($file_size > 8000000){
echo json_encode( array('status' => 'failure' , 'msg' => 'Total upload size must be less than 8 MB.') );
die();
}
if($file_tmp == ""){
echo json_encode( array('status' => 'failure' , 'msg' => 'There is no filepath.') );
die;
}
else{
if(!file_exists($upload_Path)){
move_uploaded_file($file_tmp, $upload_Path);
}
else{
$name = pathinfo($file_name, PATHINFO_FILENAME);
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$new_name = $name.rand().'.'.$ext;
$new_Path = "storage/".$new_name;
move_uploaded_file($file_tmp, $new_Path);
}
}
}
}
echo json_encode( array('status' => 'success' , 'msg' => 'File uploaded succesfully.') );
die();
}
else{
echo json_encode(array("status" => "error" , "msg" => "No file was found when processing uploaded files" ) );
die();
}
}
catch(Exception $ex){
echo json_encode(array('status' => 'error' , 'msg' => 'An unhandled exception raised: ' . $ex->getMessage() ) );
die();
}
finally{
die();
}
Then in your $.ajax() function:
$("#uploadfile").change(function(){
//submit the form here
var files = $("#fileupload")[0];
var formdata = new FormData(files);
$.ajax({
type:'POST',
url: 'mupld.php',
data: formdata,
processData:false,
contentType:false,
success: function(response){
response = JSON.parse(response);
alert(response.msg);
},
error: function(xhr, textStatus, error){
console.log('Error: '+textStatus+' '+error);
}
});
If you specifically want to handle this in the error() callback, you should set the response code of the php script to 500 -or whatever custom code- using header().

How to decode back the encoded base64 .jpeg image in AngularJS?

I have some problem in my ionic app, I want to update the image before sending it to server, so I have captured image and encoded in base64 jpeg format. I want that format to be decoded into something like "name.jpg" and it should exactly have same name what php file decode and here is my encoded code in AngularJS and decoded code in php
Angular code:
$scope.takePicture = function(source)
{
var options = {
quality : 85,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : source,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 180,
targetHeight: 180,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function(imageData) {
$scope.imgURI= "data:image/jpeg;base64," + imageData;
}, function(err) {
// An error occured. Show a message to the user
});
}
php code:
if (array_key_exists('picture', $data))
{
define('UPLOAD_DIR','../images/user_img/'); // Change your path location here and change permission to 777 ***
$img = $picture;
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$dataimg = base64_decode($img);
$filename = uniqid().'.jpeg';
$file = UPLOAD_DIR.$filename;
$success = file_put_contents($file, $dataimg);
$picture = $filename;
//log_message('info', $success ? $file : 'Unable to save the file.');
}

Categories