php - 如何在 base64 中编码 xls 文件?
问题描述
我正在使用 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 参数的本机支持,以及 PHP 在 $_FILES 参数中的本机支持,以及使用 CURLFile 类从 php-curl 获得本机支持。也很难制作一个 json 和 base64 实现,其中整个文件不必一次在内存中以创建传输请求)
推荐阅读
- java - 部署 Spring Boot + Angular 应用程序时出现问题
- html - 如何将文本放在输入表单的前面?
- javascript - 如何根据对象中的id添加键和值
- r - plot.new 之前工作时尚未调用错误
- android - 如何延迟初始化/膨胀 NavigationView
- django - 使用 Ajax 登录后,Django CSRF 验证在表单验证上失败
- dask - 如何将 Dask 与自定义类一起使用
- excel - 从不同工作表中的单个列中查找字符串并返回地址
- python - 如何将双指针 ctype 转换为 numpy 数组?
- arrays - 在 JanusGraph 中存储字节数组需要什么数据类型?