PHP Guzzle. How to set custom boundary to the multipart POST request?

旧巷老猫 提交于 2019-12-11 11:08:39

问题


How can I set custom boundary to the multipart POST request? Following request options configuration doesn't work.

'headers' => ['Content-Type' => 'multipart/form-data; boundary=CUSTOM_BOUNDARY']

回答1:


Guzzle uses psr7 to combine multipart form fields into request body. The most correct way to deal with custom boundary would be using GuzzleHttp\Psr7\MultipartStream.

$boundary = 'my_custom_boundary';
$multipart_form = [
    [
        'name' => 'upload_id',
        'contents' => $upload_id,
    ],
    [
        'name' => '_uuid',
        'contents' => $uuid,
    ],
    ...
];

$params = [
    'headers' => [
        'Connection' => 'close',
        'Content-Type' => 'multipart/form-data; boundary='.$boundary,
    ],
    'body' => new GuzzleHttp\Psr7\MultipartStream($multipart_form, $boundary), // here is all the magic
];

$res = $this->client->request($method, $url, $params);



回答2:


I'm having the same error, here's how i solve it.

//encode field
$field_string = json_encode($field_data);
//read file
$file_string = Flysystem::read($config['doc_path']);
// hack, request body, inject field and file into requet body, set boundary
$request_body =
  "\r\n"
  ."\r\n"
  ."--customboundary\r\n"
  ."Content-Type: application/json\r\n"
  ."Content-Disposition: form-data\r\n"
  ."\r\n"
  ."$field_string\r\n"
  ."--customboundary\r\n"
  ."Content-Type:application/pdf\r\n"
  ."Content-Disposition: file; filename=".$config['deal_name'].";documentid=".$config['deal_id']." \r\n"
  ."\r\n"
  ."$file_string\r\n"
  ."--customboundary--\r\n"
  ."\r\n";

//create request, boundary is required for docusign api
 $result = $this->client->createRequest('POST',"$this->baseUrl/templates", [
'headers' => [
    'Content-Type' => 'multipart/form-data;boundary=customboundary',
    'Content-Length' => strlen($request_body),
    'X-DocuSign-Authentication' => json_encode([
        'Username' => Config::get('docusign.email'),
        'Password' => Config::get('docusign.password'),
        'IntegratorKey' => Config::get('docusign.integratorKey')
    ]),
   ],
  'body' => $request_body
]);


来源:https://stackoverflow.com/questions/30963197/php-guzzle-how-to-set-custom-boundary-to-the-multipart-post-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!