基本上,我有这个表单数据我试图使用cURL传递,这里它被硬编码到边界并且只是发送请求。
$postfields = '--Boundary+0xAbCdEfGbOuNdArY'."\r\n";
$postfields .= 'Content-Disposition: form-data; name="device_timestamp"'."\r\n\r\n";
$postfields .= (time() - (100 * rand(1,6)))."\r\n";
$postfields .= '--Boundary+0xAbCdEfGbOuNdArY'."\r\n";
$postfields .= 'Content-Disposition: form-data; name="photo"; filename="photo"'."\r\n";
$postfields .= 'Content-Type: image/jpeg'."\r\n\r\n";
$postfields .= file_get_contents($path)."\r\n";
$postfields .= '--Boundary+0xAbCdEfGbOuNdArY--'."\r\n";
$result = $this->curl_request('api.com/upload/',$postfields,array(
CURLOPT_HTTPHEADER => array(
'Content-type: multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY',
'Content-Length: '.strlen($postfields),
'Expect:'
)
));
我怎样才能将这些数据传递给这样的函数?
private function multipart_build_query($fields){
$retval = '';
foreach($fields as $key => $value){
$retval .= "--".$this->boundary."\r\nContent-Disposition: form-data; name=\"$key\"\r\n\r\n$value\r\n";
}
$retval .= "--".$this->boundary."--";
return $retval;
}
由于以下行,我猜测我必须修改multipart_build_query
:Content-Type: image/jpeg
我尝试过以下
$data_array = array(
"device_timestamp" => (time() - (100 * rand(1,6))),
"photo" => "@".$path,
);
$body = $curl->multipart_build_query($data_array);
但无济于事
答案 0 :(得分:2)
我建议你制作一个这样的数组:
$time = (string) (time() - (100 * rand(1,6)));
$photo = file_get_contents($path);
$fields = array(
array(
'headers' => array(
'Content-Disposition' => 'form-data; name="device_timestamp"',
'Content-Length' => strlen($time)
),
'body' => $time
),
array(
'headers' => array(
'Content-Disposition' => 'form-data; name="photo"; filename="photo"',
'Content-Type' => 'image/jpeg',
'Content-Length' => strlen($photo)
),
'body' => $photo
)
);
该方法可以如下所示:
private function multipart_build_query($fields)
{
$data = '';
foreach ($fields as $field) {
// add boundary
$data .= '--' . $this->boundary . "\r\n";
// add headers
foreach ($field['headers'] as $header => $value) {
$data .= $header . ': ' . $value . "\r\n";
}
// add blank line
$data .= "\r\n";
// add body
$data .= $field['body'] . "\r\n";
}
// add closing boundary if there where fields
if ($data) {
$data .= $data .= '--' . $this->boundary . "--\r\n";
}
return $data;
}
您现在拥有一个支持任何类型字段的非常通用的方法。