How to send Image or file to the external API using HTTP Client?

3.3k Views Asked by At

I have an API to save images and files

this is the code to save the image request from the API

$file = $request->file('gambar');
$fileName = $file->getClientOriginalName();
$file->storeAs('images/berita', $fileName);

$berita = new Berita;
$berita->judul = $request->judul;
$berita->kategori_id = $request->kategori_id;
$berita->isi = $request->isi;
$berita->gambar = $fileName;
$berita->tgl = $request->tgl;
$berita->user_id = $request->user_id;
$berita->save();

return response()->json([
    'message' => 'Data berita Added Successfully!',
    'Added berita' => $berita
], Response::HTTP_OK);

Then on the client side, I'm using HTTP Client from Laravel to POST the data to the API. And here's the code.

$Berita = Http::withToken('xxx')
      ->attach('attachment', file_get_contents($request->file('gambar')))
      ->post('https://api.xxx.my.id/xxx', [
           'judul' => $request->judul,
           'kategori_id' => $request->kategori_id,
           'isi' => $request->isi,
           'gambar' => file_get_contents($request->file('gambar')),
           'tgl' => $request->tgl,
           'user_id' => $request->user_id
      ]);

return $Berita;

All the data send successfully, except the gambar which contains the image that i sent. It says that in my API validation.

The gambar must be a file of type: jpeg, jpg, png.

It thought that means the image that i send is sent as a string, so it didn't receive it as a file.

By the way, here's the Laravel documentation about HTTP Client: https://laravel.com/docs/9.x/http-client#multi-part-requests

Does anyone knows how to correctly using it? I think i've misused it.

2

There are 2 best solutions below

0
On

This is because the server cannot read your data.

You should send the data using the application/x-www-form-urlencoded content type, you can achieve this as Laravel documentation says:

$response = Http::asForm()->post('http://example.com/users', [
    'name' => 'Sara',
    'role' => 'Privacy Consultant',
]);
0
On

I think there is problem with attachment.

  return Http::withToken('xxx')
          ->attach('gambar', file_get_contents($request->file('gambar')), , 'gambar.png')
          ->post('https://api.xxx.my.id/xxx', [
               'judul' => $request->judul,
               'kategori_id' => $request->kategori_id,
               'isi' => $request->isi,
               'tgl' => $request->tgl,
               'user_id' => $request->user_id
          ]);

or

return Http::withToken('xxx')
      ->attach('gambar', $request->file('gambar'), 'gambar.png')
      ->post('https://api.xxx.my.id/xxx', [
           'judul' => $request->judul,
           'kategori_id' => $request->kategori_id,
           'isi' => $request->isi,
           'tgl' => $request->tgl,
           'user_id' => $request->user_id
      ]);