用 Guzzle 重写 curl(文件上传) - PHP

示例代码

我正在尝试将文件上传到我的服务器,然后将该文件发送到 Zendesk。Zendesk 文档展示了如何:

curl "https://{subdomain}.zendesk.com/api/v2/uploads.json?filename=myfile.dat&token={optional_token}" \
  -v -u {email_address}:{password} \
  -H "Content-Type: application/binary" \
  --data-binary @file.dat -X POST

这工作正常。我现在必须用 Guzzle(版本 6)重写它。我正在使用 Symfony 2.7:

$file = $request->files->get('file');

$urlAttachments = $this->params['base_url']."/api/v2/uploads.json?filename=".$file->getClientOriginalName();

$body = [
        'auth' => [$this->params['user'], $this->params['pass']],
        'multipart' => [
        [
            'name'     => $archivo->getClientOriginalName(),
            'contents' => fopen($file->getRealPath(), "r"),
        ],
    ]
];

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', $urlAttachments, $body);
$response = json_decode($response->getBody(), true);

该文件正在上传,但是当我下载它时,它还会在其内容中获取一些元数据(破坏其他一些文件类型)。我想我没有正确上传它,因为卷发的另一种方式工作正常。

--5b8003c370f19
Content-Disposition: form-data; name="test.txt"; filename="php6wiix1"
Content-Length: 1040

... The rest of the original content of the test file...

--5b8003c370f19--

我不知道为什么这些数据也作为文件的一部分发送(我不想这样做),或者是否可以为此使用 multipart 。

谢谢你的帮助!

托比亚斯 K。

可以即可使用multipart,但服务器必须正确处理它。无论您是否使用它,它都是不同的请求主体。

它通常用于具有(多个)文件上传的 HTML 表单。文件被命名(因此是元信息),所以可以有多个文件。文件中也可能有正常的表单字段(文本)。您可能可以通过搜索找到更好的解释,只是想给出一个简短的解释。

在您的情况下,服务器似乎不会以不同于“二进制帖子”的方式处理多部分表单数据,因此它会保存所有内容,包括元信息。

使用body通过原始的身体和产生您一个相同的请求curl与狂饮:

$urlAttachments = $this->params['base_url']."/api/v2/uploads.json?filename=".$file->getClientOriginalName();

$opts = [
    // auth
    'body' => fopen($file->getRealPath(), "r"),
    'headers' => ['Content-Type' => 'application/binary'],
];

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', $urlAttachments, $opts);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章