How can I POST a file to a REST server without wri

2019-05-25 02:12发布

问题:

I'm trying to send an XML file to a server as part of the POST method for an internal API.

All the PHP documentation points to using the $postVars['file']='@/path/to/file.xml' to actually send the file.

I want to send the file from a string, but it still needs to be sent as a file upload, not a string.

Help?

回答1:

Take a look at this thread it deals with what you want to do I think: http://www.webmasterworld.com/php/3164561.htm

The last entry might be of help (reformatted by me):

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; 
}

Basically the solution is to make use of the built-in php stream handling for urls.



回答2:

http://www.sematopia.com/?p=153 and http://www.daniweb.com/forums/thread150772.html might help.



标签: php rest curl