首页 > 解决方案 > 如何在 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}'

标签: phpcurlbase64

解决方案


-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 实现,其中整个文件不必一次在内存中以创建传输请求)


推荐阅读