天天看點

php curl form-data,在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

标頭設定為multipart / form-data,我想為請求中發送的每個項設定mime類型:application / octet-stream表示檔案AND application / json表示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); // false for https

$page_content = curl_exec($ch);

curl_close($ch);

如何在CURLOPT_POSTFIELDS中為資料設定application / json?

謝謝 .