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.
Related
I have a page with send data to an Lumen API. I send the data using the Laravel Http Client, like this:
$url = env('API_ADDRESS');
$data= [
'p1' => $request->input('p1'),
'p2' => $request->input('p2')
];
$headers = [
'key' => env('API_KEY')
];
$req = Http::withHeaders($headers)->post($url, $data);
The status code from this request is 200.
In my API, i have a code like to receive the data and save it:
public function SaveReq(Request $request)
{
$data = [
'status'=> 'success',
'msg'=> ''
];
try {
$req = new Requisition();
$req->p1 = $request->input('p1');
$req->p2 = $request->input('p2');
$req->save();
} catch (ErrorException $e) {
$data['status'] = 'error';
$data['msg'] = $e->getMessage();
} finally {
return json_encode($data);
}
}
In my application that send the request, i can see the json of the api returns, but the api dont save the data, but if i send a request with this same data using Postman, my api save the data.
What am i doing wrong in the application that sends the data?
check http method in your application and postman be same
before save data , use dd($request->all()); to sure data
send correctly
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;
}
Sends post request to another api inside Laravel controller.
It returns .pdf file as a response. I wanna save this file to storage. I get FileNotFound exception.
Here is the code
public function cvToPDF(Request $request)
{
$response = Http::withHeaders(['Content-Type' => 'application/pdf'])
->withToken(Request()->bearerToken())
->post('http://some-endpoint', $request->all());
Storage::disk('s3')->putFile('drive/files', $response);
return $response;
}
return $response works in client side. I can download the pdf with this endpoint. But Storage::disk raises exception.
Because you try to save response, not file.
Workaround at sink() method - this MAY work.
public function cvToPDF(Request $request)
{
$tempName = tempnam(sys_get_temp_dir(), 'response').'.pdf';
$response = Http::sink($tempName)
->withHeaders(['Content-Type' => 'application/pdf'])
->withToken(Request()->bearerToken())
->post('http://some-endpoint', $request->all());
Storage::disk('s3')->putFile('drive/files', new File($tempName));
return $response;
}
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');
I'm trying to upload a video using Laravel and GuzzleHttp to DailyMotion. Here's my code:
$file = "3.mp4";
$fields["file"] = fopen($file, 'rb');
$res = $client->post($upload_url, [
'headers' => ['Content-Type' => 'multipart/form-data'],
$fields
]);
$data3 = $res->getBody();
$response_upload_video = json_decode($data3,true);
echo "<br>Getting dm upload video response: ";
print_r($response_upload_video);
$upload_url is a dynamically generated URL passed by DailyMotion. Upon executing the code above, I'll always get this error:
Production.ERROR: GuzzleHttp\Exception\ClientException:
Client error:
POST
http://upload-02.sg1.dailymotion.com/upload?uuid=werewkrewrewrwer&seal=pppppppppppppppp`resulted
in a 400 Bad Request response:
{"error":"invalid content range","seal":"yyyyyyyyyyyyyyyyyy"}
in /home/vagrant/Code/svc-titus/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:111
But I can upload video to the same upload URL using Postman, as displayed below:
i don't think you need to specify content-type header guzzle will decide it automatically when you provide it a resource also the path of your video here seems problematic if video is stored at public directory you need to use public_path or respective path helper function to get its physical path
below should work in guzzleHttp 6 check sending form files here
http://docs.guzzlephp.org/en/latest/quickstart.html#uploading-data
$file = "3.mp4";
$res = $client->post($upload_url, [
'multipart' => [
[
'name' => 'file',
'contents' => fopen(base_path($file), 'r') // give absolute path using path helper function
]
]
]);
$data3 = $res->getBody();
$response_upload_video = json_decode($data3,true);
echo "<br>Getting dm upload video response: ";
print_r($response_upload_video);