gpt4 book ai didi

php - 使用 Guzzle 上传文件

转载 作者:可可西里 更新时间:2023-11-01 00:39:49 29 4
gpt4 key购买 nike

我有一个可以上传视频并将其发送到远程目的地的表格。我有一个 cURL 请求,我想使用 Guzzle 将其“翻译”为 PHP。

到目前为止我有这个:

public function upload(Request $request)
{
$file = $request->file('file');
$fileName = $file->getClientOriginalName();
$realPath = $file->getRealPath();

$client = new Client();
$response = $client->request('POST', 'http://mydomain.de:8080/spots', [
'multipart' => [
[
'name' => 'spotid',
'country' => 'DE',
'contents' => file_get_contents($realPath),
],
[
'type' => 'video/mp4',
],
],
]);

dd($response);

}

这是我使用的 cURL,我想将其翻译成 PHP:

curl -X POST -F 'body={"name":"Test","country":"Deutschland"};type=application/json' -F 'file=@C:\Users\PROD\Downloads\617103.mp4;type= video/mp4 ' http://mydomain.de:8080/spots

所以当我上传视频时,我想替换这个硬编码

C:\Users\PROD\Downloads\617103.mp4

当我运行它时,出现错误:

Client error: POST http://mydomain.de:8080/spots resulted in a 400 Bad Request response: request body invalid: expecting form value 'body`'

Client error: POST http://mydomain.de/spots resulted in a 400 Bad Request response: request body invalid: expecting form value 'body'

最佳答案

我会查看 Guzzle 的 multipart请求选项。我看到两个问题:

  1. JSON 数据需要进行字符串化,并使用您在 curl 请求中使用的相同名称进行传递(它的名称容易混淆 body)。
  2. curl 请求中的 type 映射到 header Content-Type。来自 $ man curl:

    You can also tell curl what Content-Type to use by using 'type='.

尝试这样的事情:

$response = $client->request('POST', 'http://mydomain.de:8080/spots', [
'multipart' => [
[
'name' => 'body',
'contents' => json_encode(['name' => 'Test', 'country' => 'Deutschland']),
'headers' => ['Content-Type' => 'application/json']
],
[
'name' => 'file',
'contents' => fopen('617103.mp4', 'r'),
'headers' => ['Content-Type' => 'video/mp4']
],
],
]);

关于php - 使用 Guzzle 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46710497/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com