我正在使用 php 将一个 xls 文件编码为 base64。然后我使用 curl 将它发送到我的服务器(使用 API)。我解码了它,但是当我下载文件时,我得到了一个无法读取的文件。
$xls = file_get_contents('/home/vacation/test.xls');
// Encode the image string data into base64
$data = base64_encode($xls);
通过 curl 发送文件
curl -X POST http://example.com/api/ -d 'data={//here goes a json with encoded file}'
-X POST
大致翻译为CURLOPT_POST=>1
并且-d 'data={//here goes a json with encoded file}'
大致翻译为CURLOPT_POSTFIELDS=>json_encode(array('data'=>'here goes encoded file'))
,所以
$ch = curl_init('http://example.com/api/');
curl_setopt_array($ch, array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode(array(
'data' => base64_encode(file_get_contents('/home/vacation/test.xls'))
))
));
curl_exec($ch);
curl_close($ch);
.. 但是为了上传二进制文件,你根本不应该使用 json/base64,你应该使用 multipart/form-data,设计那个 api 的人可能没有创建 web api 的经验,使用 json 和 base64 是一个糟糕的设计决定,海事组织。(最糟糕的部分是它使用的带宽比 multipart/form-data 大约多 33%,但是 multipart 也有来自 curl cli 的 -F 参数的原生支持,以及 $_FILES 参数中来自 PHP 的原生支持,和来自带有 CURLFile 类的 php-curl 的本机支持。也很难进行 json 和 base64 实现,其中整个文件不必一次在内存中以创建传输请求)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句