[英]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);
}
是的,您的目录不存在。
$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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.