使用 JSON 发送二进制文件内容

Sending binary file content using JSON

我已经为我的 ownCloud 应用编写了一个 REST 接口。我有方法 getFileFromRemote($path),它应该 return 一个包含文件内容的 JSON 对象。 不幸的是,这仅在我在 $path 中指定的文件是纯文本文件时才有效。当我尝试为图像或 PDF 调用方法时,状态代码为 200,但响应为空。对于 return 文件内容,我使用 file_get_contents 来检索内容。


注意:我知道ownCloud有一个WebDAV接口,但我只想用REST解决这个问题。


编辑 这是代码服务器端(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]);
}

第一行检索下载 ownCloud 服务器上的内容并完全运行。

您可能必须 base64_encode 您的文件内容才能 json_encode/decode 正确处理它:

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

然后当通过第二方接收文件时,您将必须始终:

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

这只是一个,但也是最简单的处理方法。顺便说一句,迟早你会发现 Mime-Type 在响应中会有用。