I send a png image file to controller in base64 via Ajax. I've already test and sure that controller has received id but still can't save it to public folder.
Here is my controller
public function postTest() {
$data = Input::all();
//get the base-64 from data
$base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);
//decode base64 string
$image = base64_decode($base64_str);
$png_url = "product-".time().".png";
$path = public_path('img/designs/' . $png_url);
Image::make($image->getRealPath())->save($path);
// I've tried using
// $result = file_put_contents($path, $image);
// too but still not working
$response = array(
'status' => 'success',
);
return Response::json( $response );
}
Intervention Image gets binary data using file_get_content function:
Reference : Image::make
Your controller should be look like this:
public function postTest() {
$data = Input::all();
$png_url = "product-".time().".png";
$path = public_path().'img/designs/' . $png_url;
Image::make(file_get_contents($data->base64_image))->save($path);
$response = array(
'status' => 'success',
);
return Response::json( $response );
}
$data = Input::all();
$png_url = "perfil-".time().".jpg";
$path = public_path() . "/img/designs/" . $png_url;
$img = $data['fileo'];
$img = substr($img, strpos($img, ",")+1);
$data = base64_decode($img);
$success = file_put_contents($path, $data);
print $success ? $png_url : 'Unable to save the file.';
$file = base64_decode($request['image']);
$safeName = str_random(10).'.'.'png';
$success = file_put_contents(public_path().'/uploads/'.$safeName, $file);
print $success;
This is an easy mistake.
You are using public_path incorrectly. It should be:
$path = public_path() . "/img/designs/" . $png_url;
Also, I would avoid your method of sending the image. Look at a proper upload in a form and use Laravel's Input::file method.
My solution is:
public function postTest() {
$data = Input::all();
//get the base-64 from data
$base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);
//decode base64 string
$image = base64_decode($base64_str);
Storage::disk('local')->put('imgage.png', $image);
$storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();
echo $storagePath.'imgage.png';
$response = array(
'status' => 'success',
);
return Response::json( $response );
}
what am i doing is using basic way
$file = base64_decode($request['profile_pic']);
$folderName = '/uploads/users/';
$safeName = str_random(10).'.'.'png';
$destinationPath = public_path() . $folderName;
file_put_contents(public_path().'/uploads/users/'.$safeName, $file);
//save new file path into db
$userObj->profile_pic = $safeName;
}
Store or save base64 images in the public folder image and return file path.
$folderPath = public_path() . '/' . 'images/';
$image_parts = explode(";base64,", $image);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$uniqid = uniqid();
$file = $folderPath . $uniqid . '.' . $image_type;
file_put_contents($file, $image_base64);
return $file;
Actually, Input::all() returns an array of inputs so you have following:
$data = Input::all();
Now your $data is an array not an object so you are trying to access the image as an object like:
$data->base64_image
So, it's not working. You should try using:
$image = $data['base64_image'];
Since it's (base64_image) accessible from $_POST then Input::file('base64_image') won't work because Input::file('base64_image') checks the $_FILES array and it's not there in your case.
Here is my solution for the file upload from base_64.
public static function uploadBase64File(Request $request, $requestName = 'imageData', $fileName = null, $uploadPath = 'uploads/images/')
{
try {
$requestFileData = $request->$requestName;
// decode the base64 file
$file = base64_decode(preg_replace(
'#^data:([^;]+);base64,#',
'',
$request->input($requestName)
));
if (in_array($file, ["", null, ' '])) {
return null;
}
//handle base64 encoded images here
if ($fileName == null) {
$fileName = Str::random(10);
}
$extension = '.' . explode('/', explode(':', substr($requestFileData, 0, strpos($requestFileData, ';')))[1])[1];
$filePath = $uploadPath . '' . $fileName . '' . $extension;
// dd($extension);
if (!File::exists(public_path($uploadPath))) {
File::makeDirectory(public_path($uploadPath), 0777, true);
}
// dd($filePath);
$ifImageUploadSuccessful = File::put(public_path($filePath), $file);
if (!$ifImageUploadSuccessful) {
return null;
}
return '/' . $filePath;
// throw new Exception("Unable To upload Image");
} catch (Exception $e) {
// dd($e);
throw new Exception($e->getMessage());
}
}
I'v done it!!
I replaced
$data->base64_image to $_POST['base64_image'] and then use
$result = file_put_contents($path, $image);
instead of Image::make($image->getRealPath())->save($path);
But this doesn't look like a laravel ways. I you have another way that look more elegant please tell me!
Related
I created a form to store article with an image , and generate a resized version as thumbnail from it.
I want the image to be renamed after the article slug and stored in the "public/img/articles-images " directory but i keep receiving : "Image source not readable" error
This is the image upload handler function in my controller :
private function handleRequest($request)
{
$data = $request->all();
if ($request->hasFile('image')) {
$image = $request->file('image');
$fileName = $request->slug;
$successUploaded = $image->storeAs('img/articles-images', $fileName);
if($successUploaded) {
$width = config('cms.image.thumbnail.width');
$height = config('cms.image.thumbnail.height');
$extension = $image->getClientOriginalExtension();
$thumbnail = str_replace(".{$extension}", "_thumb.{$extension}", $fileName);
Image::make('img/articles-images' . '/' . $fileName)
->resize($width, $height)
->save('img/articles-images' . '/' . $thumbnail);
}
$data['image'] = $fileName;
}
return $data;
}
storeAs() method, which receives the path, the file name, and the (optional) disk as its arguments :
$successUploaded = $request->file('image')->storeAs(
'images', $fileName
);
I solved it ! Apparently there was no need to storeAs() method at all , the new code is like below :
if ($request->hasFile('image')) {
$image = $request->file('image');
$fileName = $request->slug.'.' .$image->getClientOriginalExtension();
$destination = $this->uploadPath;
$successUploaded = $image->move($destination, $fileName);
// //
I receive a string of base64 and am able to decode it and put it into a file. The problem is, I would like to create a new image file each time to put this base64 into.
Currently I have a basic code which is able to put contents into the file that is pre-existing but the current code does not create a non-existent file.
$data = base64_decode($data);
$path = 'abc';
var_dump(is_dir($path));
if ( ! is_dir($path)) {
if(mkdir($path, 0777)) {
echo "created dir";
}
}
file_put_contents('tmp.png', $data);
Base64 function to decode
function base64ToFile($base64String, $outputFile) {
$file = fopen($outputFile, "wb");
$data = explode(',', $base64String);
fwrite($file, base64_decode($data[1]));
fclose($file);
return $outputFile;
}
Check this the function will return you the unique name after uploading your image in a directory
$imageBase64=$_POST['image_converted_base64'];//get base64 of image from client end
$unique_name =uploadSingleImage($imageBase64);//function call
//function to upload image and get an unique name to store in db
function uploadSingleImage($base64) {
$uniname = uniqid() . date("Y-m-d-H-i-s") . ".png";
$new_image_url = "../../image/" . $uniname;
$base64 = 'data:image/jpeg;base64,' . $base64;
$base64 = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64));
file_put_contents($new_image_url, $base64);
return $uniname;
}
so i'm trying to upload image from ionic app to laravel web application problem it is i don't know how to do this my controller looks like this
public function postDamage(Request $request){
try{
$damage = new damage();
$damage->type = $request->input('type');
$damage->address = $request->input('address');
$damage->description = $request->input('description');
$damage->solvedBy = $request->input('solvedBy');
$damage->userToken = $request->input('userToken');
$damage->opstina = $request->input('opstina');
$damage->image = $request->input('image');
/* $imgName="";
if ($request->hasFile('image')) {
$imgName = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $imgName);
$this->save();
return back()->with('success','Image Upload successfully');
}
$target_path = time().'.jpg';
$imagedata = $request->input('image');
$imagedata = str_replace('data:image/jpeg;base64,',$imagedata);
$imagedata = str_replace('data:image/jpg;base64,',$imagedata);
$imagedata = str_replace(' ', '+',$imagedata);
$imagedata = base64_decode($imagedata);
file_put_contents($target_path,$imagedata);
$damage->image = $imagedata; */
$damage->save();
return response()->json(['response'=>'Штетата е пратено.']);
}catch (\Exception $e){
return response()->json(['response'=>$e->getMessage()]);
}
}
now how i can post some data together with image but image to be uploaded in server. The image that is generated in ionic it is in base64.
Any method i tried from google but none of them works.
Thank you.
I am using Spatie Laravel Medialibrary to save images for my laravel models here is a git link:
https://github.com/spatie/laravel-medialibrary
then in controller
if ($f = $request->file) {
$img = explode(",", $f)[1];
$base64data = str_replace(',', '', $img);
$item->addMediaFromBase64($base64data)
->usingFileName('original.jpg')
->toMediaCollection('item');
}
now in your case that might be (not tested)
$img = explode(",", $f)[1];
$base64data = str_replace(',', '', $img);
$imagedata = base64_decode($base64data);
file_put_contents($target_path,$imagedata);
I am trying to convert and store base64 encoding to an image in laravel 5.4. Here $ifphoto has base64 value. I also checked it using return. I have visitor_photo folder in public folder. How can I store that. My controller function is here. Thanks in advance
public function store(Request $request)
{
$visitor = new visitor() ;
$ifphoto = $request->v_photo;
if (isset($ifphoto)) {
define('UPLOAD_DIR', 'public/visitor_photo/');
$encoded_data = $ifphoto;
$img = str_replace('data:image/jpeg;base64,', '', $encoded_data );
$data = base64_decode($img);
$file_name = 'image_'.date('Y-m-d-H-i-s', time()); // You can change it to anything
$file = $file_name . '.png';
$request->v_photo->move(base_path('public/visitor_photo'), $file);
// $file = UPLOAD_DIR . $file_name . '.png';
// $success = file_put_contents($file, $data);
$visitor->v_photo = $file_name;
}
$visitor->save();
return redirect('/home');
}
Below code will store your base64 string as image in app/public folder. You can change the path as per your requirement.
Code :
if (isset($ifphoto)) {
$file_name = 'image_'.date('Y-m-d-H-i-s', time()).'.png';
if($ifphoto!=""){
\Storage::disk('public')->put($file_name,base64_decode($ifphoto));
}
}
Any best way to do this will be gratefull
what this do is grab the input from a form and save it to the database.
public function update()
{
$file = Input::file('path');
$destinationPath = 'img/';
$filename = $file->getClientOriginalName();
// $extension =$file->getClientOriginalExtension();
$upload_success = Input::file('path')->move($destinationPath, $filename);
$photo = Photo::find($_POST['id']);
$photo->caption = $_POST['caption'];
$photo->path = $destinationPath . $filename;
$photo->save();
if( $upload_success ) {
return Redirect::to('photos/'.$_POST['id'].'/edit')->withInput()->with('success', 'Photo have been updated.');
} else {
return Response::json('error', 400);
}
}
this work just fine but i wonder if there a simplify way to do this like how i can get post data from the form send to update to update the photo information instead of me using the $_POST and get the id from the form parse into the update($id) ect. Thanks
You can use the Input class, instead of accessing the post directly.
I would probably re-write the function a little like this:
public function update()
{
$file = Input::file('path');
$destinationPath = 'img/';
$filename = $file->getClientOriginalName();
if( Input::file('path')->move($destinationPath, $filename) )
{
$photo = Photo::find(Input::get('id'));
$photo->caption = Input::get('caption');
$photo->path = $destinationPath . $filename;
$photo->save();
return Redirect::to('photos/'.$_POST['id'].'/edit')->withInput()->with('success', 'Photo have been updated.');
}
else
{
return Response::json('error', 400);
}
}
The other option is to extract some of this data directly into your Photo model, and do it in there.