简体   繁体   English

用curl作为字符串发布文件

[英]Posting file with curl as a string

I'm trying to upload a file using curl and php with the following code. 我正在尝试使用以下代码使用curl和php上传文件。 I'm passing post data as a string using http_build_query rather than an array because post data is a multi part array. 我使用http_build_query而不是数组将发布数据作为字符串传递,因为发布数据是一个多部分数组。 Code works except I can't get image to upload. 代码有效,但无法上传图片。

$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);

First of all make sure what you want to do. 首先确定您要做什么。 If you want to do normal form posting then remove this below header from your code, and it should work. 如果您要进行常规表单过帐,请从代码中删除下面的标头,它应该可以工作。

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));

Now, if you want to do a multipart/form-data posting through curl, then do this: 现在,如果要通过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);

Could not accomplish this using http_build_query on my multi-dimensional post array... the file will not be uploaded by the server. 无法在我的多维帖子数组上使用http_build_query来完成此操作...服务器将不会上传文件。 Had to create the array with the nested part as http does... 必须像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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM