使用Laravel上传图像文件到API



我正在尝试使用外部API调用上传文件。然而,在尝试将数据附加到请求时面临一些问题。我需要附加文件本身和文件名作为表单数据。

我已经试过了:

$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>");

但我得到错误与post()方法期望一个数组?

我也试过这样发送

$response = Http::post("<API ENDPOINt>", 
[
"multipart" => [
[
"name" => "image",
"contents" => file_get_contents("storage/app/images/".$fileName),
"filename" => $fileName,
],
[
"name" => "fileName",
"contents" => $fileName,
]
]
]);

但这也没有像预期的那样工作,我得到file_get_contents(storage/app/images/e5b7e91dfa34a94f09d200f9436ea4e3f3c0d46e-action-helicopter.jpg): Failed to open stream: No such file or directory,即使文件确实存在。

这里的任何帮助都将是感激的。不必使用这些方法,只需以任何方式POST File数据以及可以在请求的表单主体中访问的文件名。试着检查文档和其他论坛,但没有以前的答案帮助。

我用下面的命令对它进行排序:

$response = Http::attach('image', file_get_contents($file->path()), $fileName)->post("<endpoint>", [
"fileName" => $fileName
]);```

最新更新