如何通过创建目录上传base64图片并上传

How to upload base64 image by creating directory and upload

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

/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 的目录文件夹。

如果你帮助我使我的代码更合适,我将不胜感激:)

谢谢。

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()

是的,您的目录不存在。

$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 );