error('文件后缀必须为jpg,jpeg,png'); } if ($file) { //创建目录 $upload_dir = public_path() . 'public/attachment/images/' . date('Ymd'); if (!is_dir($upload_dir)) { mkdir($upload_dir, '0777', true); } //保存文件 $file_name = $this->_file_name($ext); $file_path = '/attachment/images/' . $file_name; $is_upload = $this->_base64_image_content($file, $file_path); if (!$is_upload) { page_result(1, "上传失败,请重新上传"); } $attachment = request()->domain() . $file_path; AttachmentModel::create([ 'filename' => $name, 'atype' => 1, 'attachment' => $attachment, 'createtime' => time(), ]); page_result(0, '', ['avatar' => $attachment]); } else { page_result(1, "请上传文件"); } } private function _file_name($ext) { //生成随机文件名 //定义一个包含大小写字母数字的字符串 $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //把字符串分割成数组 $newchars = str_split($chars); //打乱数组 shuffle($newchars); //从数组中随机取出15个字符 $chars_key = array_rand($newchars, 15); //把取出的字符重新组成字符串 $fnstr = ''; for ($i = 0; $i < 15; $i++) { $fnstr .= $newchars[$chars_key[$i]]; } //输出文件名并做MD5加密 return md5($fnstr . microtime(true) * 1000) . '.' . $ext; } private function _base64_image_content($base64_image_content, $file_url_path) { //匹配出图片的格式 if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) { $content = base64_decode(str_replace($result[1], '', $base64_image_content)); $file_path = public_path('') . 'public' . $file_url_path; if (file_put_contents($file_path, $content)) { return true; } else { return false; } } else { return false; } } }