我试图通过POST方法进行RESTful API调用来上传视频。我所缺乏的是我不知道编写这种API的最佳实践,我也没有在互联网上找到任何可以遵循的资源。现在我正在做这个:
我在PHP和zend框架(Zend_Rest_Route)工作。
第一种方法:
在客户端使用file_get_contents并使用curl将其POST到API,在服务器端使用file_put_contents写入数据并发送适当的响应。
第二:使用zend_file_transfer在服务器端接收文件,并将我的上传api端点的地址放在zend_form中,设置方法为post。在这种情况下,文件被上传到服务器,但在提交表单后,地址栏中的url指向api服务器,并且永远不会返回到表单。
我做的对吗?,如果没有,请告诉我最好的做法是什么,以及如何实现这一目标。
感谢您的宝贵时间。
像这样的东西为我工作:
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。)我添加了我自己的用户代理——如果您想让某些服务器认为这是一个浏览器帖子,您可能需要更改用户代理来欺骗浏览器。
您是否尝试在处理上传的控制器操作的末端添加重定向?(如果不是,你真的应该作为它的良好实践后重定向)(确保你重定向后,你的逻辑已经执行)。从本质上讲,接收帖子数据的"页面"应该只处理数据,你想要返回给用户的关于该帖子操作的任何信息都应该在你重定向他们到的页面上提供给他们。
[form]——POST->[' POST ' controller action]——redirect (302)->[page with success/failure info]