douxi4114 2015-04-19 00:58 采纳率: 100%
浏览 101

带有file_get_contents的PHP Post文件[关闭]

I need to send a file with file_get_contents function of PHP. I'm using the code below and I'm not getting ...

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

And on my server in python, I have the following code:

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()+'"}')

My Images is a Google NDB Model, with a "ndb.BlobProperty()" field.


Edited: With this CURL work's, but I can not use in production server....

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

RESOLVED:

    $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);
  • 写回答

1条回答 默认 最新

  • douou6696 2015-04-19 18:15
    关注

    You should change 'header' to 'Content-Type: application/x-www-form-urlencoded', and you wouldn't need to resort to curl. See How to post data in PHP using file_get_contents? for an example.

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法