I have a base64 image that is a very long character count and when I try to send it via Fetch POST API it gets cut off and makes the image unacceptable by my PHP file server-side. The base64 is the b64data variable in my below code. Any solutions or ideas would be appreciated!
function submitPhoto(){
fetch('http://fanbeauties.com/app/submit-photo.php?pass=MY_PASS', {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'name='+name+'&email='+email+'&market='+market+'&picture='+b64data
});
};
The PHP:
<?php
$title = $_POST['name'];
$market = $_POST['market'];
$account = "414890";
$date = date("Y-m-d");
$pass = $_GET['pass'];
$image = $_POST['picture'];
$title = $_POST['name'];
//$source_type = "app";
if($pass == "Fan412") {
//Clean base64 String
//$image = str_replace(' ', '', $image);
//Convert base64 into image
$filename_path = md5(time().uniqid()).".jpg";
$decoded=base64_decode($image);
file_put_contents("../MY_FOLDER/".$filename_path,$decoded);
// Insert Info into Database
$mysqli->query("INSERT INTO MY_TABLE (account, date, title, market, image) VALUES ('$account', '$date', '$title', '$market', '$filename_path')");
// close connection
$mysqli->close();
} else {
die();
} ?>
how about cut the base64_code into pieces then
post them before submit the whole form...
postData
{
'code': one piece_code,
'current_position': 1,
'full_pieces_count': a count you cut pieces
}
in php you can use redis to cache the base64_pieces with sorted_set piece1 piece2 ...( the score use the current_position you post)
after final pieces upload success...
combine them into pic to save then give js an img_url
then submit the whole form
btw: set the max length to post all the string...if it's too long...cut it and post them async/sync
Related
I am trying to get multiple images from the user and post it on the Facebook page using Facebook Graph API Javascript SDK. Currently, I am able to post a single image. I searched facebook documentation and got nothing except it may be possible through albums, batch requests, or adding an unpublished post and then publishing it. But I don't know about any of them exactly. Your help will be highly appreciated.
Following is the code used to publish a single image:
function postImage()
{
$uploadDirectory = "uploadedFiles/";
$filename = $_FILES["postImage"]["name"];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$uniqueName = uniqid("UP-IMG-", true) . "." . $extension;
$destinationPath = $uploadDirectory . $uniqueName;
move_uploaded_file($_FILES["postImage"]["tmp_name"], $destinationPath);
$_GET['imageUrl'] = "https://www.salebazarmzd.com/" . $destinationPath;
//creating variables to store data from Super Global Vars
$url = $_GET['imageUrl'];
$message = $_POST['postDescription'];
$link = $_POST['postLink'];
$message = $message . "\n" . $link;
$page_access_token = $_GET['page_access_token'];
$page_id = $_GET['page_id'];
echo $url;
echo $message;
$script = <<< JS
$(function() {
var form = document.querySelector('#form');
const data = Object.fromEntries(new FormData(form).entries());
console.log(data['postImage']);
var formData = {
"message": `$message`,
"url": "$url",
'access_token': "$page_access_token"
}
console.log(formData);
FB.api(
'/$page_id/photos',
'POST',
formData,
function(response) {
console.log(response);
}
)
});
JS;
return $script;
}
I have used PHP to get the file and store it on the server and then sent the request using FB.api() which is available through Facebook Graph API JavaScript SDK.
I have the below base64 string generated from an app I'm testing out. It's supposed to generate an image but I can seem to get it to validate or display in HTML. I am trying to use PHP to decode and change to a JPG file but it seems the source of the base64 string may be the issue. Any thoughts?
I actually linked the file with the base64 in here since it's so many characters.
Thanks in advance!
PHP Code:
$title = $_POST['name'];
$market = $_POST['market'];
$account = "414890";
$date = date("Y-m-d");
$pass = $_GET['pass'];
$image = $_POST['picture'];
$title = $_POST['name'];
$source_type = "app";
if($pass == "Fan412") {
//Convert base64 into image
$filename_path = md5(time().uniqid()).".jpg";
$decoded=base64_decode($image);
file_put_contents("../FOLDER_TO_IMAGES/".$filename_path,$decoded);
// Insert Info into Database
$mysqli->query("INSERT INTO TABLE_HERE (account, date, source_type, title, market, image) VALUES ('$account', '$date', '$source_type', '$title', '$market', '$filename_path')");
// close connection
$mysqli->close();
} else {
die();
}
I was introduced to Cropit recently and find it really easy to use but I am stuck at one area. I am trying to use Cropit and form submit. I am following the demo provided by Cropit.
Javascript:
$('form').submit(function() {
// Move cropped image data to hidden input
var imageData = $('.image-editor').cropit('export');
$('.hidden-image-data').val(imageData);
// Print HTTP request params
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return false;
});
PHP:
$encoded = $base64_string;
$decoded = urldecode($encoded);
$image_name = explode(';', $decoded);
$image_name = explode(':', $image_name[0]);
$image = array_pop($image_name);
$ext = explode('/', $image);
//decode the url, because we want to use decoded characters to use explode
$decoded = urldecode($encoded);
//explode at ',' - the last part should be the encoded image now
$exp = explode(',', $decoded);
//we just get the last element with array_pop
$base64 = array_pop($exp);
//decode the image and finally save it
$data = base64_decode($base64);
$str = random_string('alnum', 8);
$file = $str.'.'.$ext[1];
$data = $upload;
file_put_contents('assets/image_test/cropped/'.$file, $data);
It is able to output the file into my folder but the picture is just a blank screen with the dimension I set.
I have try to search the web but I couldn't find any solution to my problem.
Hope to get help from anyone who have encounter or know a solution.
I'm having trouble with seemingly simple problem.
Using JQuery i want to POST an array containing 2 items, an email address and email content, to a simple PHP script that mails the customer's concern back to my own server email.
I am receiving the email, but it is blank because either im not encoding or decoding the JSON object correctly or something else.
Javascript:
...
var JSONEmailRequest = new Object();
JSONEmailRequest.emailaddress = $("#emailInput").val();
JSONEmailRequest.content = $("#contentInput").val();
$.post("/email.php", JSON.stringify(JSONEmailRequest), function (data) {
//do stuff
});
...
PHP:
<?php
$POSTJSONObj = json_decode($POST['JSONEmailRequest']);
$email_to = "shawnandrews#saportfolio.ca";
$email_subject = "User enquiry from ".$POSTJSONObj['emailaddress'];
$email_body = $POSTJSONOb j['content'];
$result = mail($email_to,$email_subject,$email_body,"From: ".$email_to);
if(!$result) {
echo false;
} else {
echo true;
}
?>
Don't convert the JSONEmailRequest to JSON. $.post expects the data argument to be either an object or a string in www-form-urlencoded format. So do:
$.post("/email.php", JSONEmailRequest, function(data) {
...
}, "json");
And in the PHP code, use $_POST to get the parameters, and json_encode to send the result back.
<?php
$email_to = "shawnandrews#saportfolio.ca";
$email_subject = "User enquiry from ".$_POST['emailaddress'];
$email_body = $_POST['content'];
$result = mail($email_to,$email_subject,$email_body,"From: ".$email_to);
echo json_encode($result);
I wrote a small script using only PHP to test file download functionality using a experimental API, where this worked fine. When I decided to commit this code to my project, I added the same code to the handler for my AJAX call, however it does not start the download as it did before.
I believe this is due to the fact I am using AJAX, however as I was using header() to initiate the file download on the client, I am at a loss as to how to work around this.
Can anyone suggest an alternative method to do this now?
AJAX:
$.ajax({
type: "POST",
url: "handler.php",
data: { 'action': 'downloadFile', 'filename': curSelectedFile },
dataType: 'json',
success: function(data)
{
//Success
}
});
PHP Handler:
case "downloadFile":
{
$filename = '';
if (isset($_POST["filename"]))
{
$filename = $_POST["filename"];
}
$pos = 0; // Position in file to start reading from
$len = 32; // Length of bytes to read each iteration
$count = 0; // Counter for the number of bytes in the file
do
{
$result = $fm->getFileChunk($filename, $pos, $len);
$chunk = $result->result;
if (!empty($chunk))
{
$chunk = base64_decode($chunk);
$count += strlen($chunk);
echo $chunk;
}
$pos += $len;
}
while (!empty($chunk));
header('Content-Disposition: attachment; filename="'. $filename .'"');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . $count);
$response['status'] = "success";
echo json_encode($response);
break;
}
You can encode your file in base64 and create File Object using JavaScript.
I wouldn't recommend this for large files!
Alternative:
Save your file on server and you can just retrieve file location and redirect using location.href in Ajax callback.
You can decode base64 using atob() and create typed array. refer to following link for creating Binary Object on client side. You create typed array like answered here.