How to save PDF from base64 in database with url? - javascript

I'm generating PDF of html table. I want to save pdf in database. This script is downloading pdf. I want to send pdf file to controller side then save in database. I'm getting base64 string in controller now how i can save and retrieve with url?
var doc = new jsPDF({
unit: 'px',
format: 'a4'
});
doc.fromHTML($('#revision_table').get(0), 2, 2);
doc.save('scdedule_revision.pdf');
var pdf = doc.output();
axios.post(this.$path + 'api/savePdf', null,
{
params: {'pdf_file': doc.output('datauri')}
}
).then(({data}) => (
console.log(data)
))
.catch(error => console.log(error));
Controller:
public function savePdf(Request $request)
{
$destinationPath = 'users/pdf';
$fileuploadedpath = '';
$pdf = $request->get('pdf_file');
if ($pdf != '') {
$extension = $pdf->getClientOriginalExtension();
$fileName = rand(11111, 99999) . '.' . $extension;
$success[0] = $pdf->move($destinationPath, $fileName);
$fileuploadedpath = url($destinationPath . "/" . $fileName);
}
dd($fileuploadedpath);
}

Try this
$data = file_get_contents('string path file');
$content = base64_decode($data);

for storing the base64 into the database you need to simply store the base64 string to database column form controller
$b64Doc = base64_encode(file_get_contents($this->pdfdoc));
Now for decoding the file use the file all you need to fetch the base64 data form table and then use code below to get the PDF again
// a route is created.
$route = "pdf/".$name;
// decode base64
$pdf_b64 = base64_decode($base_64);
// you record the file in existing folder
if(file_put_contents($route, $pdf_b64)){
//just to force download by the browser
header("Content-type: application/pdf");
//print base64 decoded
echo $pdf_b64;
}

Related

base64 string won't convert to image

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();
}

base64 String is too long to send via Fetch HTTP API

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

Input Image File in VueJs + SlimPHP

I am new in VueJs, I want to input image file and some text using vuejs for creating new user. So far, I already make the base64 image, but I don't know how to pass this base64 image to the slim code in the server.
Here is my vue code:
Input File
<input class="file-input" type="file" name="userPhoto" #change="uploadPhoto">
Method :
uploadPhoto: function(e){
var reader = new FileReader()
reader.readAsDataURL(e.target.files[0])
reader.onload = (e) => {
this.usr.user_photo = e.target.result
}
}
Post :
console.log(this.usr);
this.$http.post('MyAPI', this.usr)
.then(function(response){
this.$router.push({path: '/'});
}
console.log output this object :
Image
and here is my code in slim post request
$app->post('/api/user/add', function(Request $request, Response $response){
//Upload Files
$directory = $this->get('upload_directory');
$uploadFiles = $request->getUploadedFiles();
$uploadedFile = $uploadFiles['userPhoto'];
if($uploadedFile->getError() === UPLOAD_ERR_OK){
$filename = moveUploadedFile($directory,$uploadedFile);
$response->write('Uploaded '.$filename.'<br/>');
}
function moveUploadedFile($directory, UploadedFile $uploadedFile){
$extension = pathinfo($uploadedFile->getClientFilename());
$basename = bin2hex(random_bytes(8));
$filename = sprinf('%s.%0.8s',$basename, $extension);
$uploadedFile->moveTo($directory.'/'.$filename);
return $filename;
}
$user_id = $request->getParam('user_id');
$password = $request->getParam('password');
$name = $request->getParam('name');
$status = $request->getParam('status');
$prodi = $request->getParam('prodi');
$social_link = $request->getParam('social_link');
$sql = "INSERT INTO user
VALUES (:user_id,:password,:name,:status,:prodi,CURRENT_TIMESTAMP(),'$filename',:social_link)";
try{
// Get DB Object
$db = new db();
// Connect
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->bindParam(':user_id', $user_id);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':status', $status);
$stmt->bindParam(':prodi', $prodi);
$stmt->bindParam(':social_link', $social_link);
$stmt->execute();
echo '{"notice" : {"text": "User Added"}}';
} catch(PDOException $e){
echo '{"Error": {"text": }'.$e->getMessage().'}';
}
});
I already try using resteasy and copy paste all object inside the "usr", but i got this error :
500 Internal Server Error
Can someone tell me how to do this? thanks
Your ajax request contains the image data within a json encoded attribute "user_photo" in form of a Data URI scheme.
This is not a "classic" file upload, so this code won't work like expected.
$uploadFiles = $request->getUploadedFiles();
Instead you may try to read the data URI from the json data.
$userPhoto = $request->getParam('user_photo');
Then try to decode the data URI string and save it as file.
$userPhoto = str_replace("\n", "", $userPhoto);
$userPhotoData = substr($userPhoto, strpos($userPhoto, ',') + 1);
// Decode the base64 string
$userPhotoData = base64_decode($userPhotoData);
// Save the file
file_put_contents('filename.jpg', $userPhotoData);
Notice: Never use echo in Slim. Use the response object instead.
$result = [
'notice' => [
'text' => 'User Added'
]
];
return $response->withJson($result);

How to Store Base 64 Image into Database, and to My Server Folder

How Can I Store a Base 64 Image to my Database and To my Server Folder. the Following Code is Using to Save that Image into My server Folder. but the image can't open.
$data = $src;
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = '../emailtest'.rand() . '.png';
$success = file_put_contents($file, $data);
$data = base64_decode($data);
$source_img = imagecreatefromstring($data);
$rotated_img = imagerotate($source_img, 90, 0);
$file = '../emailtest'. rand(). '.png';
$imageSave = imagejpeg($rotated_img, $file, 10);
imagedestroy($source_img);
My advice:
1. Avoid to save binary to database, save it into file if possible.
2. Prefer to save binary into blob column better than save base64 into text column. Because base64 encode make this more bigger
Here is, i try to
1. download image from url
2. save binary into file
3. save binary to db
4. convert image binary to base64
5. display image base64 using html <*img> tag
try this code
DEMO
<?php
$img_url = 'http://cdn-o7.outfit7.com/wp-content/uploads/2016/01/Icon-r-512-3.png';
$img_binary = file_get_contents($img_url);
$ext = pathinfo($img_url, PATHINFO_EXTENSION);
$img_base64 = "data:image/".$ext.";base64," . base64_encode($img_binary);
//save into file
$name = "emailtest_".rand().$ext;
file_put_contents($name, $img_binary);
echo "<img src=\"$name\" title=\"show from file\"/>";
//store to db
/* create your new table for testing
CREATE TABLE IF NOT EXISTS `table_img` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`img_binary` blob NOT NULL,
`location` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
*/
$insert="INSERT INTO table_img ('img_binary','location') VALUES('$img_binary','$name')"; //==>save to db using this query
$select="SELECT img_binary FROM table_img WHERE id=1"; //call your image binary using this query
// then convert binary into base64 with this : $img_base64= base64_encode(YOUR BINARY DATA FROM DATABASE);
//because i cant do it live in my server, i will shortcut call previous variable $img_base64 from above instead call binary from db and base64 encode
echo "<img src=\"$img_base64\" title=\"show from base64\"/>";
?>

Image corrupted when using Cropit and form submit

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.

Categories

Resources