I am trying to upload an image from my react native project using laravel as my backend framework.
This is the data I send :
I receive a warning that my network request failed.
Here is my backend code :
public function upload(Request $request)
{
$image = $request->get('data');
$name = 'Sup';
Image::make($request->get('data'))->save(public_path('images/').$name);
$fileupload = new Fileupload();
$fileupload->filename=$name;
$fileupload->save();
return response()->json(['message' => 'Success']);
}
I have a function, you can try it!
Please change the path before doing anything else (this is the code used to upload one - multiple files at once)
public function uploadImage (Request $request) {
$files = $request->file('images');
$fileText = '';
foreach($files as $file) {
$rules = array('file' => 'required|mimes:png,gif,jpeg');
$validator = Validator::make(array('file' => $file), $rules);
if($validator->passes()){
$destinationPath = 'storage/images/';
$filename = $file->getClientOriginalName();
$unique_name = md5($filename. time()).$filename;
$upload_success = $file->move($destinationPath, $unique_name);
$fileText .= url('storage/images/' . $unique_name) . '|';
}
}
return rtrim($fileText, '|');
}
I installed the patch "intervention/image", "must-master" in order to make my image to reduce the size of it to 300 by 300.
I've done some forms and appears to me always the same mistake.
Call to a member function resize() on string
which got the error?
Controller
public function updateProfile() {
$file = Input::file('imagem');
$profileData = Input::except('_token');
$validation = Validator::make($profileData, User::$profileData);
if ($validation->passes()) {
if ($file == null) {
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return view('backend/perfil.index');
}
$file = array_get($profileData,'imagem');
$destinationPath = 'imagens/perfil';
$extension = $file->getClientOriginalExtension();
$filename = rand(11111, 99999) . '.' . $extension;
$reduzir = $filename -> resize (300,300);
$profileData['imagem'] = $filename;
$upload_success = $file->move($destinationPath, $filename);
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return Redirect::to('backend/perfil');
} else {
return Redirect::to('backend/perfil')->withInput()->withErrors($validation);
}
}
The issue might be because of these reasons
Have you added this aliases in your app.php
'aliases' => [
//add these three at the bottom
'Form' => Illuminate\Html\FormFacade::class,
'HTML' => Illuminate\Html\HtmlFacade::class,
'Image' => Intervention\Image\Facades\Image::class
],
I believe that you already have form and html helper.
And use this function in the Controller
i.e., just pass the image and size value as the Parameter to this function
In the controller you have just call the below function like
$resizedImage = $this->resize($image, $request->get('image_size'));
And the resize() function was given below
private function resize($image, $size)
{
try
{
$extension = $image->getClientOriginalExtension();
$imageRealPath = $image->getRealPath();
$thumbName = 'thumb_'. $image->getClientOriginalName();
//$imageManager = new ImageManager(); // use this if you don't want facade style code
//$img = $imageManager->make($imageRealPath);
$img = Image::make($imageRealPath); // use this if you want facade style code
$img->resize(intval($size), null, function($constraint) {
$constraint->aspectRatio();
});
return $img->save(public_path('images'). '/'. $thumbName);
}
catch(Exception $e)
{
return false;
}
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!
$destinationPath = public_path().'/uploads/';
if (Input::hasFile('photo'))
{
$res = Input::file('photo')->move($destinationPath);
echo $destinationPath;
if($res)
{
echo '<br />good';
}
else
{
echo 'bad'.$res;
}
exit;
}
my enctype form is enctype="multipart/form-data", the uploads folder exists and its access is 777, the above statement returns good, the path is correct, what I'am doing wrong?
$photo = Input::file('photo');
if (Input::hasFile('photo'))
{
$file = Input::file('photo');
$destinationPath = public_path().'/uploads/';
$filename = $file->getClientOriginalName();
$uploadSuccess = $file->move($destinationPath, $filename);
$user->logo_path = $filename;
}
$object->save();
// Don't forget to save it using a save function, otherwise your hard work will be for nothing
// $object : use your object like user, car, ...
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.