我正在使用一个API,可以将文件发送到类似于Dropbox的地方。根据文档,发送的文件需要是BASE64编码数据。
因此,我正在尝试类似于这样的方法:
$b64Doc = chunk_split(base64_encode($this->pdfdoc));
其中$this->pdfdoc
是我的PDF文档的路径。
目前,文件已发送,但似乎无效(未显示任何内容)。
我是否正确地将我的PDF转换为BASE64编码的数据?
谢谢
base64_encode
接受一个字符串输入。所以你要做的就是对路径进行编码。你应该抓取文件的内容。
$b64Doc = chunk_split(base64_encode(file_get_contents($this->pdfdoc)));
base64_encode()
函数将对传递给它的任何字符串进行编码。如果您传递的值是文件名,则会得到一个编码后的文件名,而不是文件内容。
您可能需要先执行file_get_contents($this->pdfdoc)
或其他操作。
// Real date format (xxx-xx-xx)
$toDay = date("Y-m-d");
// we give the file a random name
$name = "archive_".$toDay."_XXXXX_.pdf";
// a route is created, (it must already be created in its repository(pdf)).
$rute = "pdf/".$name;
// decode base64
$pdf_b64 = base64_decode($base_64);
// you record the file in existing folder
if(file_put_contents($rute, $pdf_b64)){
//just to force download by the browser
header("Content-type: application/pdf");
//print base64 decoded
echo $pdf_b64;
}
chunk_split()
函数可以将一个字符串分割成较小的块,这对于例如将base64_encode()输出转换为符合RFC 2045语义非常有用。它会在每个长度字符处插入分隔符。来源:https://www.php.net/manual/en/function.chunk-split.php - Vincent V