John Davidson

php - how to upload image using http client laravel to API

0 comments
Message:


I want to update/upload an image using http client laravel. I did update the data but the image are not updated. the API are blob type. I try to use form-data file in postman and it did work. but I don't know why it's not working in my laravel app.


this is my code


$image = $request->file('profile_image');
if ($image != null) {
$contents = $image->openFile()->fread($image->getSize());
}
$response = Http::withToken($request->session()->get('user'))->acceptJson()->attach('image', file_get_contents($image))->post("https://voice.infidea.id/api/gateway/update-user", [
'id' => $user['id'],
'name' => $request->name,
'email' => $request->email,
'contact' => $request->contact
]);

I try to use the $content also but still did not work. only the string data that updated.



My Answer:
To upload an image using HTTP client in Laravel, you can use the `attach` method to attach the image file to the request. Here's an example code snippet that shows how you can upload an image using HTTP client in Laravel:

php
$image = $request->file('profile_image');

if ($image != null) {
$response = Http::withToken($request->session()->get('user'))
->attach('image', file_get_contents($image), $image->getClientOriginalName())
->post("https://voice.infidea.id/api/gateway/update-user", [
'id' => $user['id'],
'name' => $request->name,
'email' => $request->email,
'contact' => $request->contact
]);
} else {
$response = Http::withToken($request->session()->get('user'))
->post("https://voice.infidea.id/api/gateway/update-user", [
'id' => $user['id'],
'name' => $request->name,
'email' => $request->email,
'contact' => $request->contact
]);
}



In this code snippet, we first check if the image file is present in the request. If it is, we attach the image file to the request using the `attach` method. We also pass the original file name of the image as the third parameter to the `attach` method.

Then, we make a POST request to the API endpoint with the image file attached along with other form data. If the image file is not present, we make a POST request without attaching the image file.

Make sure to replace `'profile_image'` with the name of the input field that contains the image file in your form.

This should allow you to upload an image using HTTP client in Laravel to the API.

Rate this post

4 of 5 based on 5944 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us