Reputation: 37
I am trying to upload a file using an external API call. However facing some issues when trying to attach the data to the request. I need to attach the file itself and the file name as form data.
I have tried the following:
$response = Http::attach('image', $file->path(), $fileName)->withOptions([
"multipart" => [
"name" => "image",
"contents" => fopen($file->path(), "r"),
"filename" => $fileName,
],
[
"name" => "fileName",
"contents" => $fileName
]
])->post("<API-ENDPOINT>");
But I am getting errors with the post() method expecting an array?
I tried sending it this way too
$response = Http::post("<API ENDPOINt>",
[
"multipart" => [
[
"name" => "image",
"contents" => file_get_contents("storage/app/images/".$fileName),
"filename" => $fileName,
],
[
"name" => "fileName",
"contents" => $fileName,
]
]
]);
But this didn't work as expected either, I am getting file_get_contents(storage/app/images/e5b7e91dfa34a94f09d200f9436ea4e3f3c0d46e-action-helicopter.jpg): Failed to open stream: No such file or directory
even though the file does exist.
Any help here would be appreciated. Doesn't have to use these methods, just any way to POST the File data along with the filename that can be accessed in the form body of the request. Tried checking docs and other forums but no previous answers helped.
Upvotes: 1
Views: 684
Reputation: 37
I got it sorted by using the below:
$response = Http::attach('image', file_get_contents($file->path()), $fileName)->post("<endpoint>", [
"fileName" => $fileName
]);```
Upvotes: 2