[英]PHP force download base64image
我想提供一个 PNG 图像仅供某些用户下载,并且该图像不应位于任何地方,因此用户不应看到它的路径。
这就是为什么我将它作为 base64 图像插入到 download.php 中的原因。 问题是,虽然提供图像供下载,但下载时显示 0 B 大小。
$base64strImg = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAxoAAARjCAIAAABnqMWCAAAACXBIWXM...';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=myimage.png');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
ob_clean();
flush();
readfile(base64_decode($base64strImg));
exit;
不知道问题出在哪里,如果它无法处理大图像或为什么无法下载。
我也试过这种方式:
header('Content-Disposition: attachment;filename="test.png"');
header('Content-Type: application/force-download');
echo base64_decode($base64strImg);
现在图像大小正确,但下载后仍然无法打开。 图像查看器显示不支持的格式。
第三个选项 - 不解码,它也有正确的大小,但仍然无法打开。
header('Content-Description: File Transfer');
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename=test.png');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . strlen($base64strImg));
ob_clean();
flush();
echo $base64strImg;
exit;
根据@Lawrence 的建议,我更新了我的代码,它的工作方式如下:
$resultimg = str_replace("data:image/png;base64,","",$base64strImg);
header('Content-Disposition: attachment;filename="test.png"');
header('Content-Type: image/png');
echo base64_decode($resultimg);
您不必做所有事情,您只需上传图像并通过 htaccess 或权限限制对它的访问,并使用带有 download.php 标头的 readfile 并检查用户是否有权下载文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.