小编jej*_*eje的帖子

在 php curl multipart/form-data 请求中发送一个文件和 json 数据

我正在尝试在 PHP 的curl 请求中上传文件和json 数据。该请求在命令行中使用curl 可以正常工作。这是命令行中的curl请求:

curl -v --basic -u'username' -F file="@documentTest.pdf;type=application/octet-stream" -F data='{"nomDocument":"test.pdf","externalid":"123456"};type=application/json' https://server.com/api/sendDocument
Run Code Online (Sandbox Code Playgroud)

标头设置为 multipart/form-data,我想为请求中发送的每个项目设置 mime 类型:文件的 application/octet-stream 和 json 数据的 application/json 。

这是我的 PHP 代码

$dataJson = '{"nomDocument":"test.pdf","externalid":"123456"}';

$header = array('Authorization: Basic c2fghEfgfhVDZkOWxfghfghfgUy', 'Content-Type: multipart/form-data');

$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt(
    $ch, CURLOPT_POSTFIELDS, array(
        'file' => new \CurlFile(realpath('documentTest.pdf'), 'application/octet-stream', 'test.pdf'),
        'data' => $dataJson
    )
);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, 'https://server.com/api/sendDocument');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); …
Run Code Online (Sandbox Code Playgroud)

php json curl mime-types php-curl

5
推荐指数
0
解决办法
3772
查看次数

标签 统计

curl ×1

json ×1

mime-types ×1

php ×1

php-curl ×1