PHP - 文件上传

private function upload($_FILES)
{
    $file = array();
    if (!empty($_FILES['name'])) {
        $file_name = $_FILES['name'];
        $file_type = $_FILES['type'];
        $file_tmp_name = $_FILES['tmp_name'];
        $file_error = $_FILES['error'];
        $size = $_FILES['size'];
        //
        $allowSub = array('.jpg', '.gif', '.jpeg', '.png');
        $fileSub = strtolower(strrchr($file_name, '.'));
        //文件大小于5M
        if ($size > 5242880){
            $file['error'] = "上传文件过大,请上传小于5M的文件";
            return $file;
        }
        if (!in_array($fileSub, $allowSub)) {
            $file['error'] = "请上传JPG,GIF,PNG格式的图片";
            return $file;
        }
        //
        $allowMine = array('image/png', 'image/jpg', 'image/gif', 'image/jpeg', 'image/pjpeg');
        if (!in_array($file_type, $allowMine)) {
            $file['error'] = "文件格式错误".$file_type;
            return $file;
        }
        //
        $file_path = ROOT.'upload/smrz/';
        if (!file_exists($file_path)) {
            mkdir($file_path, 0777);
        } else {
            if (!is_writable($file_path)) {
                chmod($file_path, 0777);
            }
        }
        $file_new_path = date('Ymd').'_'.uniqid().$fileSub;
        if (!$file_error) {
            if (is_uploaded_file($file_tmp_name)) {
                if (move_uploaded_file($file_tmp_name, $file_path.$file_new_path)) {
                    $file['name'] = $file_new_path;
                    return $file;
                }
            }
        } else {
            switch ($file_error) {
                case 1:
                    $file['error'] = '上传文件过大,请上传小于5M的文件';
                    break;
                case 2:
                    $file['error'] = '上传文件过大,请上传小于5M的文件';
                    break;
                case 3:
                    $file['error'] = '文件只有部分上传。';
                    break;
                case 4:
                    $file['error'] = '没有文件上传';
                    break;
                case 6:
                    $file['error'] = '找不到临时文件';
                    break;
                case 7:
                    $file['error'] = '文件写入失败';
                    break;
            }
            return $file;
        }
    } else {
        $file['error'] = '没有发现上传文件';
        return $file;
}

<!--前端-->
<input type="file" name="preview" accept=".jpg,.png">
//后端
$upload = self::upload($_FILES['preview']);
//上传至服务器的文件名
$uploadName = $upload['name'];
//拼接文件链接地址
$uplaodUrl = "upload/".$uploadName;
返回文章列表 文章二维码 打赏
本页链接的二维码
打赏二维码
期待你的评论