davorminchorov's avatar

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?

0 likes
7 replies
davorminchorov's avatar

@Tray2 I am already doing that, I tried with file_get_contents but that did not work, tried with the content of the file, that did not work either.

davorminchorov's avatar

@tray2 only when I add the headers

->withHeaders([
     'Accept' => 'application/json',
    'Content-Type' => 'multipart/form-data',
])

which gets to the validation part and that's good but the file validation fails because the file is missing or is not a file type, not the correct mime type of PDF as well as the size not being correct, if I pass it as a stream with fopen().

davorminchorov's avatar
davorminchorov
OP
Best Answer
Level 53

I managed to fix the issue, in case someone else gets stuck, I'll post the solution here.

There were 2 issues:

  1. 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.
  2. 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.