PHP upload file with api - php

I am developing an api endpoint to use with my laravel and vue app.
public function avatar(Request $request)
{
$user = User::find(Auth::id());
$validator = Validator::make($request->all(), [
'avatar' => 'required'
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()]);
} else {
$image = $request->get('avatar');
//base64_decode($file_data)
$path = Storage::putFile('avatars', base64_decode($image));
$user->avatar_url = $path;
if ($user->save()) {
//return redirect()->route('user_profile_settings');
}
}
}
This is the code that I have I tried going off what I found online to accomplish file uploads with an api and using php, but I am getting this error "Call to a member function hashName() on string". The goal of this is to upload the file to a s3 bucket using the putFile method.

I believe your problem lies here:
$image = $request->get('avatar');
$path = Storage::putFile('avatars', base64_decode($image));
Per the docs, you're going to want to use $request->file('avatar') to access the file.
Then, you can do store('avatars') to store it in your default storage location.
In short:
$path = $request->file('avatar')->store('avatars');

Related

How to show response path when update image in laravel rest api?

I'm trying to build a REST API with Laravel where users need to update their images. In this case the image has been successfully saved in storage, but I want a response in the form of a link that can be accessed by the frontend later. However, the response was not found. Is there a solution to this problem? Here I attach my code
public function update(Request $request,$userId)
{
$user= User::find($userId->id);
// $photoWithExt= $request->file('photo')->getClientOriginalName();
$filename = $user['nip'];
$extension = $request->file('photo')->getClientOriginalExtension();
$fileNameToStore ='/images/users/'.$filename.'.'.$extension;
$path= $request->file('photo')->storeAs('',$fileNameToStore);
$user->update([
'username'=>$request['username'],
'name'=>$request['name'],
'photo'=> $path
]);
return $user;
}
This is response in postman
And when I click the link path, the image is 404. I hope someone can help with this problem
Assuming that you're using Local Drive, you have to get the absolute link to the file
(...)
$user->update([
'username'=>$request['username'],
'name'=>$request['name'],
'photo'=> Storage::disk('local')->get($path); // <---
]);
return $user;
}
I have found the answer,
public function update(Request $request,$userId)
{
$user= User::find($userId->id);
$filename = $user['nip'];
$extension = $request->file('photo')->getClientOriginalExtension();
$fileNameToStore ='images/users/'.$filename.'.'.$extension;
$path= $request->file('photo')->storeAs('',$fileNameToStore,'public');
$photoURL = Storage::url($path); //base_url
$user->update([
'username'=>$request['username'],
'name'=>$request['name'],
'photo'=> $photoURL,
]);
return $user;
}

Request $request convert to Array $data

I'm new at laravel and i was reading the document for a week now. i was working on crud about modification of register form i'm almost finish but then i bump in to this problem which is now i'm trying to look for a right syntax on my question would be how to i check and move a file use as a parameter to store and create a path folder for the image. similar to the code below i show using Request. cause if you look at the register page controller at the create function the parameter used is array.
tried reading documents and research couldn't find any or maybe i lack of keywords to direct me into this type of problem.
I have this code and this is right
public function store(Request $Request)
{
$ProfileUser = new User();
if($Request->hasfile('Img1'))
{
$file = $Request->file('Img1');
$extension = $file->getClientOriginalExtension(); // Get Image Ext.
$filename = time() . "." . $extension;
$file->move('uploads/employee/', $filename);
$ProfileUser->image1 = $filename;
} else
{
return $Request;
$ProfileUser->image1 = 'no image';
}
$ProfileUser->fname = $Request->input('fname');
$ProfileUser->mname = $Request->input('mname');
$ProfileUser->lname = $Request->input('lname');
$ProfileUser->homeaddress = $Request->input('homeaddr');
$ProfileUser->mobilenum = $Request->input('mobilenum');
$ProfileUser->accounttype = $Request->input('typeAcc');
$ProfileUser->image1 = $Request->input('img1');
$ProfileUser->save();
return redirect()->route('home');
}
but then i also have this modification in make:auth i made and added columns
this is my problem here since the function is using an array instead of the Request.
protected function create(array $data) <-- this is the Error
{
if($data->hasFile('image1')) { <-- from here to:
$file = $data->file('image1');
$extension = $file->getClientOriginalExtension(); // Get Image Ext.
$filename = time() . "." . $extension;
$file->move('uploads/employee/', $filename);
} else {
return $request;
} <-- here this function
$user = User::create([
'name' => $data['fname'] . " " . $data['lname'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'fname' => $data['fname'],
'mname' => $data['mname'],
'lname' => $data['lname'],
'homeaddress' => $data['homeaddr'],
'mobilenum' => $data['mobilenum'],
'accounttype' => $data['typeAcc'],
'image1' => $data['image1']
]);
return $user;
}
if i commend out the file validation the create function work fine and is able to save to database but then i need the image to be move on the 1st function it works perfect but in the 2nd using a parameter array doesn't i know i have maybe a wrong syntax which i ask for now how. and if it's ok can you guys explain a bit about the difference between Request vs Array? that i may able also to understand both
The $Request variable contains an object from the Laravel Request class (Illuminate \ Http \ Request). Read more about here
An Array is a PHP data structure. Read about arrays in PHP here.
To get all request's data as an array, you can call the method all() on the request object. It will give you an associative array.
$request->all();

Laravel: can't get post data using Postman form-data

Currently I'm developing a RESTful API so I created a method to upload images but can't the post data using Postman form-data
Here's the screenshot of the request on the Postman.
I've tried to print the request but still can't get the data.
Upload image code
public function fileUpload(Request $request, $id)
{
//print_r($request->file('photo'));
//exit;
$rules = [
'photo' => 'image|mimes:jpeg,jpg,png|max:2048'
];
$this->validate($request, $rules);
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$filename = time().'.'.$file->getClientOriginalExtension();
$request->file('photo')->move(public_path('storage/images'), $filename);
}
return response()->json(['message' => 'Image successfully uploaded'], 200);
}
I want to get post data(photo) through laravel request.

laravel 5.4 herokuapp throws an error when uploading image to google drive

Uploading Images using google drive api and it works fine locally but throws an error on heroku
ErrorException in GoogleDriveAdapter.php line 1143:
A non well formed numeric value encountered
public function store() {
$validator = Validator::make(request()->all(), [
'img' => 'required|image'
]);
if ($validator->fails()) {
return response()->json('err');
} else {
$path = request()->file('img')->store('');
$url = Storage::url($path);
auth()->user()->addImage($url);
return response()->json($url);
}
}

How to download a file with RESTFUL cakePHP 2.3

I am using CakePHP 2.3 and I have two apps on 2 different servers. I am required to download a file from the first server using REST. I have made my applications RestFul and have configured the routes. I am able to post, get, put and delete but I cannot get it done to download the file.
Below is a sample code for a get
public function view($id) {
$object = $this->Imodel->find('first', array('conditions' => array('Imodel.id' => $id), 'contain' => array()));
$this->set(array(
'object' => $object,
'_serialize' => array('object')
));
}
I would appreciate any help to download a file with REST, complying with the Restful architecture that I already have in place.
Edit
After some time, I finally got it to work. In case someone else runs into the same problem, the whole thing was about understanding cakePHP HttpSocket better.
So first on the server where the webservice is registered (where we download the file from), below is my function; its response is a file as explained (here)
public function getpdffile($id = NULL){
$filepath = APP. 'Files/file.pdf'; //path to the file of interest
$this->response->file($filepath);
return $this->response;
}
Since the file was not public (not in webroot), i had to use MediaView. Then after setting this, I'd retrieve it for download using HttpSocket as shown below:
public function download($id = NULL, $fileMine = 'pdf', $fileName = 'file', $download = TRUE){
$httpSocket = new HttpSocket();
$filepath = APP. 'Files/myfile.pdf';
$file = fopen($filepath, 'w');
$httpSocket->setContentResource($file);
$link = MAIN_SERVER."rest_models/getpdffile/".$id.".json";
$httpSocket->get($link);
fclose($file);
$this->response->file($filepath);
return $this->response;
}
What I did there was copy the file to the App folder of my server and render it in a view.
I hope it helps someone :-)
On the server which call the file to download :
$file = file_get_contents(urlwhereyoudownload) ;
And on the server where webservice is register :
header('Content-type: $mimetypeoffile');
header('Content-Disposition: attachment; filename=".$fileName."');
readfile("$pathtofile");exit;

Categories