// 使用钩子来处理有文件的上传.
if($hasFile){
$hooks = new \Requests_Hooks();
$hooks->register('curl.before_send', function($fp, $data=array(
"file" => "@/Applications/XAMPP/xamppfiles/htdocs/Public/Work/image/icon.png"
)){
curl_setopt($fp, CURLOPT_POSTFIELDS, $data);
});
$response = \Requests::post($url, $headers, array(), array('hooks' => $hooks));
}else{
$response = \Requests::post($url, $headers, $data);
}
基本原理: curl 请求发送前,重写 CURLOPT_POSTFIELDS 的值.
Requests 不直接支持 文件上传的原因: 会把$data编码;但是只有数组形式的参数才可以实现文件上传.
参考代码:
$file = 'file'; //要上传的文件
$url = 'url';//target url
$fields['f'] = '@'.$file;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields );
curl_exec( $ch );
if ($error = curl_error($ch) ) {
die($error);
}
curl_close($ch);