I am passing single base64 string as of now,but Now I need to pass multiple base64 string and sent through PHP script to the server.
as of now my code send only single data
$imagebase64 //it contains base64 array like -['data:image/jpeg;base64,/9j/4A','data:image/jpeg;base64,/9j/4A']
$("#downloadAll").click(function () {
$.ajax({
type: "POST",
url: "imageUpload.php",
data: {
// Sending single as of now
base64Img: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAADâĤ1jSchh2MkeFK5Anv7fbTv5SKFqOFdOvm764mRVLQgtO8RoP/Z",
},
contentType: "application/octet-stream",
error: function (err) {
console.log("There was an error. Try again please!", err);
},
success: function (msg) {
console.log(msg);
},
});
});
PHP Script
$base64string = $_POST['data'];
$uploadpath = 'image-cropper';
$parts = explode(";base64,", $base64string);
$imageparts = explode("image/", #$parts[0]);
$imagetype = $imageparts[1];
$imagebase64 = base64_decode($parts[1]);
$file = $uploadpath . uniqid() . '.jpeg';
file_put_contents($file, $imagebase64);
After Updated Code as suggested-
Notice: Undefined index: data in /var/www/html/image-cropper/imageUpload.php on line 1
and empty array() posted to upload.php
Ajax call:
$("#downloadAll").click(function () {
var imagebase64 = "<?= $imagebase64 ?>";
$.ajax({
type: "POST",
url: "imageUpload.php",
data: { imagesBase64: JSON.stringify(imagesBase64) },
contentType: "application/json; charset=utf-8",
error: function (err) {
console.log("There was an error. Try again please!", err);
},
success: function (msg) {
console.log(msg);
},
});
});
PHP:
$base64string = $_POST['data'];
$uploadpath = 'image-cropper';
$parts = explode(";base64,", $base64string);
$imageparts = explode("image/", #$parts[0]);
$imagetype = $imageparts[1];
$imagebase64 = base64_decode($parts[1]);
$file = $uploadpath . uniqid() . '.jpeg';
file_put_contents($file, $imagebase64);
As I understand by your first code - your array has base64 data which is already in strings so no need to convert it again.
$("#downloadAll").click(function () {
$.ajax({
type: "POST",
url: "imageUpload.php",
data: { data: imagesBase64 },
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
console.log(data);
},
});
});
As I saw your PHP script has a lot of issues, it was made only to handle a single item, you need to iterate over the array too.
$data = ($_POST['data']);
foreach($data as $base64_string ){
$filename_path = md5(time().uniqid()).".jpeg"; //use png or jpg if required
$base64_string = str_replace('data:image/jpeg;base64,', '', $base64_string);
$base64_string = str_replace(' ', '+', $base64_string);
$decoded = base64_decode($base64_string);
//defining path
file_put_contents("image-cropper".$filename_path,$decoded);
}
Related
Need to save some big data to file on server
"/php/test.php":
<?php if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";
$file = fopen("upload/" .$fname, 'w');
fwrite($file, $data);
fclose($file);
}
?>
jquery:
var data = 'foo bar';
$.ajax({
url: 'php/test.php',
type: 'POST',
data: { data: data },
success: function(result) {
alert('the data was successfully sent to the server');
}
});
result:
405 (HTTP method POST is not supported by this URL)
what's the problem?
I am trying to upload an image through ajax and needs to get the image URL as response.
code below..
$(".filupldt").on('change',function(){
var file_data=$(this).prop("files")[0];
var form_data=new FormData();
form_data.append("file",file_data);
form_data.append("type",$(this).prev().prev().val());
form_data.append("primerkey",$(this).prev().val());
var element = this;
$.ajax({
type:'POST',
mimeType: 'multipart/form-data',
url:'includes/dealerimg.settings.php?operation=savedealerimgeqtype',
dataType:'json',
async:false,
processData: false,
cache: false,
contentType: false,
data:form_data,
success:function(response){
console.log(response);
//$(element).parent().prev().prev().attr('src',response);
},
});
});
PHP Ajax function
$createthumb = new createthumb();
$todburl = $this->url;
$ajaxtype = $_POST['type'];
$uploads_dir = "../assets/equipmenttype/";
$uniid = uniqid();
$now =date('Y-m-d H:i:s');
$pkid = $_POST['primerkey'];
$ext =pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$filename = $pkid."_".$DealerID."_dealerupdate";
$thumbnamer = $pkid."_".$DealerID."_thumb_dealerupdate_".$uniid.".".$ext;
$tmpname = $_FILES['file']['tmp_name'];
$imagename = $_FILES['file']['name'];
$loc_thumb = $uploads_dir.$thumbnamer;
$createthumb->create_thumb_with_ratio($tmpname,300,300,$loc_thumb); //CREATING THUMB
$createthumb->upload_original(1,$filename,$imagename,$tmpname,$uploads_dir);//for upload original
$thumnametodb = $thumbnamer;
$orinametodb = $filename."_".$imagename;
$data = ['dddd'=>$todburl."assets/equipmenttype/".$thumbnamer];
header('Content-Type: application/json');
echo json_encode($data);
This function working perfectly and creating thumb in my required folder.
But this is an ajax page and I want to show the image name as response.
In this case the ajax response is like below attached image.
How can i solve this issue ?
Thanks
You said that you want to show the image name as response :
Then just
echo $_FILES['file']['name'];
then in your script you get the image name as response with :
success:function(response){
console.log('Image Name = '+response);
}
Your current response is JSON representation (json_encode($data)) & not the image's name.
Probably some output is braking the response data. To be sure that nothing prints on the response page try putting ob_start() and ob_end_clean()
ob_start();
//...
// your code here
//...
$data['dddd'] = $todburl."assets/equipmenttype/".$thumbnamer;
ob_end_clean();
echo json_encode($data);
I've been able to sent FormData from angularJS to php, but I don't know how to do the reverse. I'm currently trying to get the $base64 variable into my angularJS, but I'm quite stumped on how to go about doing so. The documentation in the official angularJS doesn't help me much either
https://docs.angularjs.org/api/ng/service/$http
JS
$scope.MakeGray_Button = function(){
if ($scope.imageUrl) {
var MakeGray_Form = new FormData();
MakeGray_Form.append("FileName", $scope.imageUrl);
$http({
method : "POST",
url : "../opencv/MakeGray/MakeGray.php",
data : MakeGray_Form,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
success(function(){
// some magic code here that grabs the $base64 variable from php
})
.error(function(){});
}
else{
alert("Please upload an image");
}
}
PHP
<?php
$imgname = $_POST["FileName"];
$inputDir = "../../uploads/" . $imgname;
$outputDir = "../../processed/" . $imgname;
$MakeGray = "./makegray " . $inputDir . " " . $outputDir;
$runExec = exec($MakeGray, $out);
$type = pathinfo($outputDir, PATHINFO_EXTENSION);
$data = file_get_contents($outputDir);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo "$base64";
?>
You can add a parameter in success callback to fetch the response from server if available.
var base64 = '';
$http({
method : "POST",
url : "../opencv/MakeGray/MakeGray.php",
data : MakeGray_Form,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
success(function(response){
base64 = response; //response will contain whatever server echos to it's standard output
})
.error(function(){});
you can get the response from server by using
.then(function (data) {}
and in "data" variable you can find the value you're looking for
I'm trying to capture audiorecorder (https://github.com/cwilso/AudioRecorder) and send the blob through Ajax a php file, which will receive the blob content and create the file(the wave file in this case).
Ajax call:
audioRecorder.exportWAV(function(blob) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
console.log(url);
var filename = <?php echo $filename;?>;
$.ajaxFileUpload({
url : "lib/vocal_render.php",
secureuri :false,
dataType : blob.type,
data: blob,
success: function(data, status) {
if(data.status != 'error')
alert("boa!");
}
});
});
and my php file (vocal_render.php):
<?php
if(!empty($_POST)){
$data = implode($_POST); //transforms the char array with the blob url to a string
$fname = "11" . ".wav";
$file = fopen("../ext/wav/testes/" .$fname, 'w');
fwrite($file, $data);
fclose($file);
}?>
P.S:I'm newbie with blobs and ajax.
Thanks in advance.
Try uploading the file as form data
audioRecorder.exportWAV(function(blob) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
console.log(url);
var filename = <?php echo $filename;?>;
var data = new FormData();
data.append('file', blob);
$.ajax({
url : "lib/vocal_render.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function(data) {
alert("boa!");
},
error: function() {
alert("not so boa!");
}
});
});
.
<?php
if(isset($_FILES['file']) and !$_FILES['file']['error']){
$fname = "11" . ".wav";
move_uploaded_file($_FILES['file']['tmp_name'], "../ext/wav/testes/" . $fname);
}
?>
According to the documentation, by using XMLHttpRequest.send() you can use the Blob object directly.
var blob = new Blob(chunks, { 'type' : 'audio/webm' });
var xhr = new XMLHttpRequest();
xhr.open('POST', '/speech', true);
xhr.onload = function(e) {
console.log('Sent');
};
xhr.send(blob);
I've tried this and it works like a charm.
var name = $("#name").val();
$.ajax({
type: "post",
dataType: "json",
url: "save.php",
data: {
image: canvas.toDataURL(),
name:name
}
});
I'm trying to save my cropped image with name from get text field.
When I sent only imageurl its working. How can I fix this problem ?
save.php:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
// location to save cropped image,
$ad=$_POST['name'];
$url = 'temp/"'.$ad.'".jpg';
//$url = 'temp/one.jpg';
// remove the base64 part
$base64 = preg_replace('#^data:image/[^;]+;base64,#', '', $_POST['image']);
$base64 = base64_decode($base64);
$source = imagecreatefromstring($base64); // create
imagejpeg($source, $url, 100); // save image
// return URL
$validation = array (
'url' => $url);
echo json_encode($validation);
}