这样的事情对我有用:
public function postAttachment($fileName, $fileMimetype, $fileContents, $postURL, $username, $password)
{
$auth = base64_encode($username . ':' . base64_decode($password));
$header = array("Authorization: Basic ".$auth);
array_push($header, "Accept: */*");
$boundary = "----------------------------".substr(md5(rand(0,32000)), 0, 12);
$data = "";
$data .= "--".$boundary."\r\n";
//Collect Filedata
$data .= "Content-Disposition: form-data; name=\"file\"; filename=\"".$fileName."\"\r\n";
$data .= "Content-Type: ".$fileMimetype."\r\n";
$data .= "\r\n";
$data .= $fileContents."\r\n";
$data .= "--".$boundary."--";
// add more parameters or files here
array_push($header, 'Content-Type: multipart/form-data; boundary='.$boundary);
$params = array('http' => array(
'method' => 'POST',
'protocol_version' => 1.1,
'user_agent' => 'File Upload Agent',
'header' => $header,
'content' => $data
));
$ctx = stream_context_create($params);
$fp = fopen($postURL, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with ".$postURL." ".$php_errormsg);
}
$responseBody = @stream_get_contents($fp);
if ($responseBody === false) {
throw new Exception("Problem reading data from ".$postURL.", ".$php_errormsg);
}
}
如果您想发布多个文件,或添加其他多部分参数,也可以轻松地将这些添加到其他边界。
我在另一篇文章中找到了其中一些代码,您可能可以在 PHP wiki (http://www.php.net/manual/en/function.stream-context-create.php#90411) 中找到类似的代码)。但是......该代码没有正确处理回车+换行符,我的服务器立即拒绝了该帖子。此外,旧代码还使用 HTTP 1.0 版——(它不重用套接字)。使用 HTTP 1.1 时,在发布大量文件时会重新使用套接字。 (这也适用于 HTTPS。)我添加了自己的用户代理 - 如果您正在欺骗某些服务器认为这是浏览器帖子,您可能需要更改用户代理以欺骗浏览器。