将PDF文件用PHP进行base64编码

25

我正在使用一个API,可以将文件发送到类似于Dropbox的地方。根据文档,发送的文件需要是BASE64编码数据。

因此,我正在尝试类似于这样的方法:

$b64Doc = chunk_split(base64_encode($this->pdfdoc));

其中$this->pdfdoc是我的PDF文档的路径。

目前,文件已发送,但似乎无效(未显示任何内容)。

我是否正确地将我的PDF转换为BASE64编码的数据?

谢谢

3个回答

54

base64_encode 接受一个字符串输入。所以你要做的就是对路径进行编码。你应该抓取文件的内容。

$b64Doc = chunk_split(base64_encode(file_get_contents($this->pdfdoc)));

为什么这里需要使用chunk_split()函数? - Trần Hữu Hiền
1
从php文档中得知:chunk_split()函数可以将一个字符串分割成较小的块,这对于例如将base64_encode()输出转换为符合RFC 2045语义非常有用。它会在每个长度字符处插入分隔符。来源:https://www.php.net/manual/en/function.chunk-split.php - Vincent V

6

base64_encode()函数将对传递给它的任何字符串进行编码。如果您传递的值是文件名,则会得到一个编码后的文件名,而不是文件内容。

您可能需要先执行file_get_contents($this->pdfdoc)或其他操作。


3
将base64编码转换为pdf并保存至服务器路径。
// 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;
}

1
这并没有回答问题。你正在解码,而原帖是关于编码的。 - Machavity

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接