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

时间:2018-08-24 13:31:36

标签: php curl guzzle symfony-2.7 zendesk-api

我正在尝试将文件上传到服务器,然后将该文件发送到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--

我不知道为什么这些数据也作为文件的一部分发送(我不想发送),或者可以使用多部分处理。

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

使用$discount 可以,但是服务器必须正确处理。是否使用它是一个不同的请求主体。

通常在具有(多个)文件上传的HTML表单中使用。文件被命名(因此是元信息),因此可以有多个文件。文件中也可能有普通的表单字段(文本)。您可能会发现它的by searching更好的解释,只是想给出一个简短的解释。

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

使用body传递原始内容,并用食尸鬼向您的DB::table('quantity_discounts') ->where('min_amount', $discount['min_amount']) ->where('user_id', $old['user_id']) ->where('group_id', $old['group_id']) ->where('product_id', $id) ->update($discount); 发出相同的请求:

multipart