如何使用RESTFUL cakePHP 2.3下载文件

时间:2014-12-01 13:21:21

标签: php rest cakephp cakephp-2.3 restful-architecture

我正在使用CakePHP 2.3,我在两个不同的服务器上有两个应用程序。我需要使用REST从第一台服务器下载文件。我已经使我的应用程序RestFul并配置了路由。我能够发布,获取,放置和删除但我无法完成下载文件。 以下是get

的示例代码
 public function view($id) {
    $object = $this->Imodel->find('first', array('conditions' => array('Imodel.id' => $id), 'contain' => array()));
    $this->set(array(
        'object' => $object,
        '_serialize' => array('object')
    ));
}

我很感激有任何帮助下载REST文件,遵守我已经拥有的Restful架构。

修改 过了一段时间,我终于开始工作了。如果其他人遇到同样的问题,整个事情就是更好地理解cakePHP HttpSocket。 首先在注册webservice的服务器上(我们从中下载文件),下面是我的函数;它的响应是一个文件(here

public function getpdffile($id = NULL){
    $filepath = APP. 'Files' .DS. 'file.pdf'; //path to the file of interest
    $this->response->file($filepath);
    return $this->response;
}

由于该文件不公开(不在webroot中),我必须使用MediaView。设置完成后,我会使用HttpSocket检索下载内容,如下所示:

public function download($id = NULL, $fileMine = 'pdf', $fileName = 'file', $download = TRUE){
    $httpSocket = new HttpSocket();
    $filepath = APP. 'Files'. DS. 'myfile.pdf';
    $file = fopen($filepath, 'w');
    $httpSocket->setContentResource($file);
    $link = MAIN_PROJECT_SERVER."rest_internal_applications/getpdffile/".$id.".json";
    $httpSocket->get($link);
    fclose($file);
    $this->response->file($filepath);
    return $this->response;
}

我在那里做的是将文件复制到我的服务器的App文件夹并在视图中呈现它。 我希望它可以帮助某人:-)

1 个答案:

答案 0 :(得分:1)

在调用要下载的文件的服务器上:

$file = file_get_contents(urlwhereyoudownload) ; 

在webservice注册的服务器上:

header('Content-type: $mimetypeoffile');
header('Content-Disposition: attachment; filename=".$fileName."');
readfile("$pathtofile");exit;