5

Thank you in advance,

I have one controller function like

public function storeBlog(Request $request)
{
  // Here i am receiving file like $request->file('image');
}

Now I want to send that file to an API endpoint like

Http::post('http://example.com/v1/blog/store', $request->all());

I am getting all the request but not file, I know we need to pass POST data as a multipart but how that I don't know

can anyone help

Ronak Solanki
  • 341
  • 2
  • 5
  • 14
  • I think you want to store image using api? – Irshad Khan Sep 15 '20 at 07:39
  • what have you tryed ? what are you using client side, a simple form, Javascript or a mobile device? Have you checked other question related to file upload ? – N69S Sep 15 '20 at 07:51
  • see here there is an example of using multipart request li laravel doc https://laravel.com/docs/7.x/http-client#request-data – bhucho Sep 15 '20 at 08:17

1 Answers1

20

You should use Http::attach to upload a file.

public function storeBlog(Request $request)
{
    // check file is present and has no problem uploading it
    if ($request->hasFile('image') && $request->file('photo')->isValid()) {
        // get Illuminate\Http\UploadedFile instance
        $image = $request->file('image');

        // post request with attachment
        Http::attach('attachment', file_get_contents($image), 'image.jpg')
            ->post('example.com/v1/blog/store', $request->all());
    } else {
        Http::post('http://example.com/v1/blog/store', $request->all());
    }
}
koko-js478
  • 1,703
  • 7
  • 17
  • 1
    Your answer was very helpful but the file content was missing so i have just changed bit your code to Http::attach('attachment', file_get_contents($image), 'image.jpg') ->post('http://example.com/v1/blog/store', $request->all()); and it is working as expected Thank you so much – Ronak Solanki Sep 15 '20 at 13:06
  • 1
    Sorry for the incomplete answer. Updated answer by your advice. It's a pleasure to help you. – koko-js478 Sep 15 '20 at 17:27
  • You can use `$request->file('image')` directly inside `attach` (or use `$image->get()`) – Theraloss Oct 27 '20 at 17:00