PHP上传图片类Upload.php

本文介绍了一个用于PHP图片上传的Upload.php类,结合HTML表单和JavaScript异步文件上传实现,通过ajax_file_upload.js实现无刷新上传。
摘要由CSDN通过智能技术生成

php文件Upload.php类:

<?php
/**
 * @Author: zm.wu
 * 上传类
 * 只需要实例化后调用uploadFile()方法
 */
namespace app\common;

class Uploads
{
	// 上传路径 ./ 意思是index.php下的当前目录
	protected $path = "./uploads/images/";
	// 允许上传文件最大值 5M 转换成字节
	protected $max_size = 5 * 1024 * 1024;
	// 允许上传文件后缀
	protected $ext = ['jpg', 'jpeg', 'gif', 'png', 'wbmp', 'bmp'];
	// 类型
	protected $mime = ['image/jpg', 'image/jpeg', 'image/gif', 'image/png', 'image/wbmp', 'image/bmpp'];
	// 文件新名字
	protected $new_file_name = '';

	// 存放上传文件的原信息,里面有字段:tmp_name,size,name,type,error
	protected $upload_file_array = [];

	/**
	 * __construct 构造函数
	 */
	public function __construct()
	{
		if($this->path){
			// 自动加上日期如20211224/文件夹
			$this->path = $this->path.date('Ymd', time()).'/';
		}
	}

	/**
	 * 上传文件
	 * @return array()
	 */
	public function uploadFile()
	{

		// 没有设置上传路径
		if(!$this->path){
			return $this->outMessage('文件路径没有设置');
		}

		if(!$this->checkPath()){
			return $this->outMessage('文件路径不是目录或者不可写');
		}

		if(!$this->getUploadFile()){
			return $this->outMessage('获取上传文件源错误');
		}

		if(!$this->checkSize()){
			return $this->outMessage('文件超过指定大小');
		}

		if(!$this->checkExt()){
			return $this->outMessage('文件后缀不符合');
		}

		if(!$this->checkMime()){
			return $this->outMessage('文件类型不符合');
		}

		// 是否通过http post 上传的
		if(!is_uploaded_file($this->upload_file_array['tmp_name'])){
			return $this->outMessage('不是通过指定的HTTP POST 方式上传');
		}

		$this->new_file_name = $this->createNewFileName();

		// 开始上传
		$is_move_succ = move_uploaded_file($this->upload_file_array['tmp_name'], $this->path.$this->new_file_name);

		if(!$is_move_succ){
			return $this->outMessage('移动文件失败,上传失败');
		}

		// 上传成功拼接路径
		$pic_path = substr($this->path, 1).$this->new_file_name;

		// 获取拼接当前网站域名
		$domain = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];
		$result = array(
			'img' => $domain.$pic_path,
			'info' => $pic_path,
			'path' => $_SERVER['DOCUMENT_ROOT'].$pic_path,
			'title' => $this->upload_file_array['name'],
		);

		return $this->outMessage('上传成功', true, $result);

	}



	/**
	 * 获取上传的文件源
	 * @return [type] [description]
	 */
	public function getUploadFile()
	{
		if(empty($_FILES)) return false;
		foreach($_FILES as $tmp){
			$this->upload_file_array = $tmp;
		}
		return $this->upload_file_array['error']>0? false : true;
	}

	/**
	 * 判断文件大小
	 * @return [
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值