You need to attach the file https://laravel.com/docs/9.x/http-client#multi-part-requests
Apr 8, 2022
7
Level 53
How to upload files between 2 Laravel apps?
Hi, I am trying to upload a file using the Laravel HTTP Client from the monolith Laravel API to a microservice Laravel API using something like this:
$response = $this->request->attach('file', $file)
->post($this->config->get('services.myservice.url') . self::ENDPOINT, [
'password' => $password,
'folder_name' => $folderName,
'file_name' => $fileName,
])->throw()->json();
and so far I’ve noticed that the requests work only if there are no files uploaded, I can clearly see the microservice returning some JSON from the correct endpoint, but whenever I try to upload a file using the example above, the JSON that I have in my web “/” route is being returned, no error, no info about what might be the issue.
Anyone ever had a scenario like this that might know what might be missing?
Level 53
I managed to fix the issue, in case someone else gets stuck, I'll post the solution here.
There were 2 issues:
- The file format was , it did not work as an UploadedFile instance or a string (the content of the file with file_get_conttents($file), but rather it worked as a stream.
- The Accept header only, did not need to add the Content-Type header at all.
Here's an example:
$response = $this->request->attach('file', fopen($file->getRealPath(), 'r'))
->withHeaders([
'Accept' => 'application/json'
])
->post($this->config->get('services.myservice.url') . self::ENDPOINT, [
'password' => $password,
'folder_name' => $folderName,
'file_name' => $fileName,
])->throw()->json();
Please or to participate in this conversation.