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