Thymeleaf
Thymeleaf

Reputation: 113

Sending an image with HTTP POST

Recently I wanted to separate my project in different services to I wanted to make blogs independent from the project.

In the first project i have written this code. I want to send the data that i get from the form to another API http://127.0.0.1:100/api/saveBlog

public function update(Request $request, $blog)
    {
        if (!$blog instanceof Blog) {
            $blog = $this->getById($blog);
        }


        $response = Http::post("http://127.0.0.1:100/api/saveBlog",[
           'name' =>   $request->input('name'),
            'description' => $request->input('description'),
            'name' =>  $request->input('name'),
            'photto' => $request->file('photto')
        ]);

        
        dd($response->status());

    }

In the API service i am trying to read the data

Route::post("/saveBlog",function (Request $request){
    $blog = new Blog();
    $blog->name = $request->input('name');
    $blog->description = $request->input('description');
    $blog->name = $request->input('name');
    $main = $request->file('photto');
    $fileName = microtime() . '.' . $main->getClientOriginalExtension();
    $img = Image::make($main->getRealPath());
    $img->resize(400, 400);
    $img->stream();
    Storage::disk('local')->put('public/blogs/' . $fileName, $img, 'public');
    $blog->image_path = "/storage/blogs/" . $fileName;

    return $blog->save();

});

But i am getting 500 status error and blog is not being saved in database. I think the problem is with $request->file('photto')

ANY IDEA?

Upvotes: 0

Views: 830

Answers (1)

John Lobo
John Lobo

Reputation: 15319

check whether image exist in request like below

if($request->has('photto')){
 $main = $request->file('photto');
    $fileName = microtime() . '.' . $main->getClientOriginalExtension();
    $img = Image::make($main->getRealPath());
    $img->resize(400, 400);
    $img->stream();
    Storage::disk('local')->put('public/blogs/' . $fileName, $img, 'public');
    $blog->image_path = "/storage/blogs/" . $fileName;
}

Updates

$photo = fopen(public_path('/storage/filename'), 'r');

$response = Http::
    attach('photo', $photo)
    ->post($url, [
                   'param_1' => 'param_1 contents',
                    ...
            ]);

Upvotes: 1

Related Questions