[英]Posting file with curl as a string
我正在嘗試使用以下代碼使用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);
首先確定您要做什么。 如果您要進行常規表單過帳,請從代碼中刪除下面的標頭,它應該可以工作。
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);
無法在我的多維帖子數組上使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.