使用file_put_contents上载时损坏的文件


damaged file during upload with file_put_contents

我尝试使用file_put_contents在目录中上传图像,文件已上传,但已损坏,无法打开。这是我的代码:

define('UploadDir','../Dir/images');
$path = "image.png";
$data="..."; //image base64 string
$file = UploadDir ."/". $path;
$success = file_put_contents($file, $data);
echo $success ? $file : 'Unable to save the file.';

$data="…"//基于图像的64字符串

假设$data包含注释所说的内容,如果在图像中放入base64字符串,那么它显然不是有效的图像——它将是一个包含base64编码字符串的文件。

为了有效(或有机会有效),在将字符串写入文件之前对其进行解码:

$data="..."; //image base64 string
$file = UploadDir ."/". $path;
$success = file_put_contents($file, base64_decode($data));

目录是../Dir/images chmoded to 777吗?有时php不允许您访问权限不足的目录。试着看看它是否有足够的权限,如果没有,则将其设置为777并尝试。