我想将图像上传到以下文件夹结构中:
/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
的目录文件夹中。
如果你能帮助我使我的代码更加正确,我将不胜感激:)
谢谢。
是的,您的目录不存在。
$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 );
file_put_contents
不创建目录:所以使用:
if (!is_dir('upload/usersimage/'.$Year.'/'.$Month.'/'.$Day.'' . $month)) {
mkdir('upload/usersimage/'.$Year.'/'.$Month.'/'.$Day.' . $month);
}
请参阅此处:运行file_put_contents()时创建文件夹