2015-04-19 65 views
1

我需要发送一个带有file_get_contents函数的文件。我使用下面的代码,我没有得到......PHP Post file with file_get_contents

$image['tmp_name'] = "/tmp/unnamed.png"; 
$image['file_image'] = base64_encode(file_get_contents("/tmp/unnamed.png")); 
$image['name']  = "unnamed.png"; 
$image['file_name'] = "unnamed.png"; 
$image['type']  = "image/png"; 
$image['submit'] = "UPLOAD"; 

$url = 'http://localhost/api/upload_image'; 

$postdata = http_build_query(
    array(
     'file_name' => 'form variable1', 
     'file_image' => file_get_contents($image['tmp_name']) 
    ) 
); 

$opts = array('http' => 
    array(
     'method' => 'POST', 
     'header' => 'Content-Type: multipart/form-data', 
     'content' => $postdata 
    ) 
); 

$context = stream_context_create($opts); 

var_export(file_get_contents($url, false, $context)); 

和我的蟒蛇服务器上,我有以下代码:

class UploadImage(webapp.RequestHandler): 
    def post(self): 
     img   = Images() 
     img.image = self.request.get('file_image') 
     img.name = self.request.get('file_name') or "no name" 
     img.put() 

     self.response.headers.add_header('content-type', 'application/json', charset='utf-8') 
     self.response.out.write('{"status": "OK", "image": "'+img.key.urlsafe()+'"}') 

我的图片是谷歌的NDB模式,并带有“ndb.BlobProperty()”字段。


编辑: 有了这个CURL工作的,但我不能在生产服务器上使用....

$ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($image)); 

    $exec = curl_exec($ch); 
    $info = curl_getinfo($ch); 
    curl_close($ch); 

    var_export($exec); 

解决:

$image['file_image'] = base64_encode(file_get_contents($image['tmp_name'])); 
    $image['file_name'] = "unnamed.png"; 

    $postdata = http_build_query($image); 

    $opts = array('http' => 
     array(
      'method' => 'POST', 
      'content' => $postdata 
     ) 
    ); 

    $context = stream_context_create($opts); 

    $result = file_get_contents($url, false, $data); 
    $info = $this->parse_http_response_header($http_response_header); 

    var_export($result); 
+0

我认为你没有权限访问CURL吗? '$ image'数组的目的是什么? – Devon

+0

是的,我没有访问CURL ... :( 我使用图像作为数组来模拟表单提交标记 – Augusto

+0

没有错误坚持在您的PHP文件。你确定错误是与PHP文件?您是否独立测试了Python文件? – Devon

回答

1

你应该改变'他ader'改为'Content-Type:application/x-www-form-urlencoded',你就不需要诉诸卷曲。一个例子见How to post data in PHP using file_get_contents?

+0

'multipart/form-data'应该是一个有效的内容类型。是否有某处指出fil e_get_contents不支持这个? – Devon

+0

multipart/form-data确实是一个有效的内容类型,但不使用http_build_query来构造它。有关更多详细信息,请参阅http://stackoverflow.com/questions/4003989/upload-a-file-using-file-get-contents。 – Mars