通过php发布文件“multipart / form-data”

时间:2010-09-07 23:04:09

标签: php api post

我试图在php中使用imageshshack api

以下列方式:

<?php
function do_post_request($url, $data, $optional_headers = null) {
  $params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));
  if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'rb', false, $ctx);
  if (!$fp) {
    throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
  }
  return $response;
}

    $fileName = $_FILES['picture']['name'];
    $tmpName = $_FILES['picture']['tmp_name'];
    $fileSize = $_FILES['picture']['size'];
    $fileType = $_FILES['picture']['type'];
    $fo = @fopen($tmpName, "r");
    $imgposted = @fread($fo, filesize($tmpName));
    $imgposted = addslashes($imgposted);

    $data = 'fileupload='.$imgposted.'&rembar=1&key=******';
    echo do_post_request('http://www.imageshack.us/upload_api.php',$data);

?>

但数据正常发布,我希望发布,就好像我有一个具有此属性的表单:

enctype="multipart/form-data"

任何解决方案?

2 个答案:

答案 0 :(得分:0)


do_post_request(
    'http://www.imageshack.us/upload_api.php',
    $data,
    'Content-Type: multipart/form-data')
);

答案 1 :(得分:0)

您需要将其设置为标题:

$optional_headers = array(
  'Content-Type'=>'multipart/form-data'
);

调用函数时:

do_post_request('http://www.imageshack.us/upload_api.php', array(
   'Content-Type'=>'multipart/form-data'
));

编辑:我认为您还必须url_encode而不是addslashes