gpt4 book ai didi

php解码base 64非常大的文件,而不是字符串

转载 作者:行者123 更新时间:2023-12-02 21:45:58 26 4
gpt4 key购买 nike

我有一个系统,可以在从电子邮件文件中剥离文件后,以 Base 64 编码将文件保存到服务器硬盘上。

我想再次将文件更改为其原始格式,我该如何在 php 中做到这一点?

这就是我尝试保存文件的方式,但似乎没有创建有效的文件:

$start = $part['starting-pos-body'];
$end = $part['ending-pos-body'];
$len = $end-$start;
$written = 0;
$write = 2028;
$body = '';
while ($start <= $end) {
fseek($this->stream, $start, SEEK_SET);
$my = fread($this->stream, $write);
fwrite($temp_fp, base64_decode($my));
$start += $write;
}
fclose($temp_fp);

最佳答案

@traylz 清楚地说明了为什么它可能会在不应该失败的情况下失败。但是,base64_decode() 即使对于大图像也可能会失败。我曾经处理过 6 到 7 MB 的文件,还没有超过这个大小,所以对我来说它应该很简单:

$dir = dirname(__FILE__);
// get the base64 encoded file and decode it
$o_en = file_get_contents($dir . '/base64.txt');
$d = base64_decode($o_en);

// put decoded string into tmp file
file_put_contents($dir . '/base64_d', $d);

// get mime type (note: mime_content_type() is deprecated in favour
// for fileinfo functions)
$mime = str_replace('image/', '.', mime_content_type($dir . '/base64_d'));
rename($dir . '/base64_d', $dir . '/base64_d' . $mime);

如果以下失败,请尝试添加 chunk_split() 函数来解码操作:

$d = base64_decode(chunk_split($o_en));

所以我在说什么...除非有需要,否则忘记循环...如果您不信任 php 的 mime 检测,请保留原始文件扩展名。如果处理大文件,请在 base64_decode() 操作上使用 chunk_split()

注意:所有理论都未经测试

编辑:对于很可能会卡住file_get_contents()的大文件,读取您需要的内容,输出到文件,以便使用很少的RAM:

$chunkSize = 1024;
$src = fopen('base64.txt', 'rb');
$dst = fopen('binary.mime', 'wb');
while (!feof($src)) {
fwrite($dst, base64_decode(fread($src, $chunkSize)));
}

关于php解码base 64非常大的文件,而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19510580/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com