如何通过创建目录和上传来上传base64图像

时间:2016-04-07 09:23:09

标签: php image file-upload image-uploading

我想将图片上传到以下文件夹结构中:

/var/www/html/project/public/upload/userimage/2016/04/07/thumbnail/image.png
                                               ^   ^  ^
                                            Year Month Date

我写了这段代码:

$Day = date('d'); // Get date
$Month = date('m'); // Get month
$Year = date('Y'); // Get year

$data = $_POST['base64']; // Get base64 image data

$imageName = hash('ripemd160', time()).'.png';

if (!file_exists(public_path().'/upload/userimage/'.$Year.'/'.$Month.'/'.$Day.'/thumbnail')) {
    mkdir(public_path().'/upload/userimage/'.$Year.'/'.$Month.'/'.$Day.'/thumbnail', 0777, true);
}
$url = public_path().'/upload/userimage/'.$Year.'/'.$Month.'/'.$Day.'/thumbnail/'.$imageName;

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);
file_put_contents($url.'/'.$imageName, $data);

并收到此错误:

file_put_contents(/var/www/html/project/project/public/upload/userimage/2016/04/07/thumbnail/8b38eb25ce97d428afcd80d6ddcd16b8ca266a52.png/8b38eb25ce97d428afcd80d6ddcd16b8ca266a52.png): failed to open stream: No such file or directory

如果更改Year -> Month -> Date,我只想将图片上传到目录文件夹并生成文件夹Year/Month/Date

如果您帮助我更准确地使用我的代码,我将不胜感激:)

感谢。

2 个答案:

答案 0 :(得分:1)

file_put_contents无法创建目录: 所以使用:

if (!is_dir('upload/usersimage/'.$Year.'/'.$Month.'/'.$Day.'' . $month)) {
    mkdir('upload/usersimage/'.$Year.'/'.$Month.'/'.$Day.' . $month);
}

见这里:Creating a folder when I run file_put_contents()

答案 1 :(得分:1)

是的,您的目录不存在。

$url = public_path().'/upload/userimage/'.$Year.'/'.$Month.'/'.$Day.'/thumbnail/'.$imageName;
#                                                                                 ----------
file_put_contents($url.'/'.$imageName, $data);
#                          ----------

您可以创建此目录:

/My/New/Directory

然后你尝试写这个文件:

/My/New/Directory/Image.jpg/Image.jpg

使用此命令:

file_put_contents( $url , $data );

一般建议:使用变量而不是重复连接模式,特别是如果你有很长的连接。您的代码更清晰,代码维护更容易,拼写错误的风险更低:

$dirPath = public_path().'/upload/userimage/'.$Year.'/'.$Month.'/'.$Day.'/thumbnail';
if( !file_exists( $dirPath ) )      
    mkdir( $dirPath, 0777, true );
}
$filePath = $dirPath.'/'.$imageName;
(...)
file_put_contents( $filePath , $data );