How to download a file with RESTFUL cakePHP 2.3

840 Views Asked by At

I am using CakePHP 2.3 and I have two apps on 2 different servers. I am required to download a file from the first server using REST. I have made my applications RestFul and have configured the routes. I am able to post, get, put and delete but I cannot get it done to download the file. Below is a sample code for a 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')
    ));
}

I would appreciate any help to download a file with REST, complying with the Restful architecture that I already have in place.

Edit After some time, I finally got it to work. In case someone else runs into the same problem, the whole thing was about understanding cakePHP HttpSocket better. So first on the server where the webservice is registered (where we download the file from), below is my function; its response is a file as explained (here)

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

Since the file was not public (not in webroot), i had to use MediaView. Then after setting this, I'd retrieve it for download using HttpSocket as shown below:

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

What I did there was copy the file to the App folder of my server and render it in a view. I hope it helps someone :-)

1

There are 1 best solutions below

0
On

On the server which call the file to download :

$file = file_get_contents(urlwhereyoudownload) ; 

And on the server where webservice is register :

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