我尝试使用curl和php上传文件,并使用以下代码。我使用http_build_query而不是数组将后期数据作为字符串传递,因为后期数据是多部分数组。代码有效,但我无法上传图片。
$ch = curl_init();
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIE, $cookie1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$image=file_get_contents(realpath('image.jpg'));
$postFields = array(
'authenticity_token'=>$token1.'=',
'menu_item'=>array('name' => $name,
'body'=>'',
'published'=>0,
'published'=>1,
'picture'=>$image,
);
$postData=http_build_query($postFields);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_exec ($ch);
答案 0 :(得分:0)
首先确保你想做什么。如果你想进行正常的表单发布,那么从代码中删除下面的标题,它应该可以工作。
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
现在,如果您想通过curl进行multipart/form-data
发布,请执行以下操作:
$postFields = array(
'authenticity_token'=>$token1.'=',
'menu_item'=>array('name' => $name,
'body'=>'',
'published'=>0,
'published'=>1,
'picture'=> '@' . $image, // better to use path like 'c:/temp/image.jpg'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
答案 1 :(得分:0)
无法在我的多维帖子阵列上使用http_build_query完成此操作...服务器不会上传该文件。必须创建具有嵌套部分的数组,如http ...
$postFields['authenticity_token'=$token1.'=';
$postFields['menu_item[name]']=$name;
$postFields['menu_item[body]']='';
$postFields['menu_item[published]']=0;
$postFields['menu_item[published]']=1;
$postFields['menu_item[picture]']='@'.$image;
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);