Sending binary file content using JSON

user2810895 picture user2810895 · Apr 23, 2015 · Viewed 7.1k times · Source

I've written a REST interface for my ownCloud app. I've method getFileFromRemote($path) which should return a JSON object with the file content. Unfortunately this only works when the file that I've specified in $path is a plaintext file. When I try to call the method for an image or PDF the status code is 200 but the response is empty. For returning the file contents I use file_get_contents for retrieving the content.


Note: I know ownCloud has a WebDAV interface, but I want to solve this with REST only.


EDIT This is the code server side (ownCloud):

public function synchroniseDown($path)
{
    $this->_syncService->download(array($path));//get latest version
    $content = file_get_contents($this->_homeFolder.urldecode($path));
    return new DataResponse(['path'=>$path, 'fileContent'=>$content]);
}

The first line retrieves downloades the content on the ownCloud server and works completely.

Answer

yergo picture yergo · Apr 23, 2015

You probably have to base64_encode your file content to make json_encode/decode handle it properly:

return new DataResponse([
    'path'=>$path,
    'fileContent' => base64_encode($content)  // convert binary data to alphanum
]);

and then when receiving file via second side, you will have to always:

$fileContent = base64_decode($response['fileContent']);

It's only one, but ones of easiest way to handle that. Btw, sooner or later you will find that Mime-Type would be useful in response.