图片上传出错

时间:2012-11-23 07:48:05

标签: php curl multipartform-data

我想发布一些数据,包括一个图像。我在php中使用curl。我的代码如下 -

 $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux i686; rv:6.0) Gecko/20100101 Firefox/6.0Mozilla/4.0 (compatible;)");
    curl_setopt($ch, CURLOPT_URL, 'http://postacity.co.uk:8080/shine/pp/upload/');
    curl_setopt($ch, CURLOPT_POST, true);
    $post = array(
        'creatorid' => '119',
        'userfile' => '@/temp/fgf.jpg',
        'notice' => 'Image1',
        'catid' => '1',
        'title' => 'bookofzeus',
        'boardid' => '332',
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    $response = curl_exec($ch);
    if(curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    }
    else {
        echo $response;
    }
    }

每次我收到同样的错误

  

错误:创建formpost数据失败

我是否有任何错误。我已经搜索过这个问题,但仍未找到解决方案。

2 个答案:

答案 0 :(得分:1)

文件的路径是问题:'@/temp/fgf.jpg'

你应该看看这个bug gescription:Bug 50060 - failed creating formpost data if post array value starts with @

此问题的解决方案,例如php freaks

并使用绝对路径指向文件。

答案 1 :(得分:1)

参考其工作

<?php
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
    curl_setopt($ch, CURLOPT_URL, _VIRUS_SCAN_URL);
    curl_setopt($ch, CURLOPT_POST, true);
    // same as <input type="file" name="file_box">
    $post = array(
        "file_box"=>"@/path/to/myfile.jpg",
        "username"=>"foobar",
        "password"=>"secret",
        "submit"=>"submit"
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 
    $response = curl_exec($ch);
?>

另请参阅此网址

http://joshhighland.com/blog/2010/11/27/using-curl-and-php-to-upload-files-through-a-form-post/

http://blogs.digitss.com/php/curl-php/posting-or-uploading-files-using-curl-with-php/