PHP实现的文件上传类与用法详解


Posted in PHP onJuly 05, 2017

本文实例讲述了PHP实现的文件上传类与用法。分享给大家供大家参考,具体如下:

FileUpload.class.php,其中用到了两个常量,可在网站配置文件中定义:define('ROOT_PATH',dirname(__FILE__)); //网站根目录、define('UPDIR','/uploads/'); //上传主目录

<?php
  //上传文件类
  class FileUpload {
    private $error;  //错误代码
    private $maxsize; //表单最大值
    private $type;  //类型
    private $typeArr = array('image/jpeg','image/pjpeg','image/png','image/x-png','image/gif'); //类型合集
    private $path;  //目录路径
    private $today;  //今天目录
    private $name;  //文件名
    private $tmp;  //临时文件
    private $linkpath; //链接路径
    private $linktotay; //今天目录(相对)
    //构造方法,初始化
    public function __construct($_file,$_maxsize) {
       $this->error = $_FILES[$_file]['error'];
       $this->maxsize = $_maxsize / 1024;
       $this->type = $_FILES[$_file]['type'];
       $this->path = ROOT_PATH.UPDIR;
       $this->linktotay = date('Ymd').'/';
       $this->today = $this->path.$this->linktotay;
       $this->name = $_FILES[$_file]['name'];
       $this->tmp = $_FILES[$_file]['tmp_name'];
       $this->checkError();
       $this->checkType();
       $this->checkPath();
       $this->moveUpload();
    }
    //返回路径
    public function getPath() {
       $_path = $_SERVER["SCRIPT_NAME"];
       $_dir = dirname(dirname($_path));
       if ($_dir == '\\') $_dir = '/';
       $this->linkpath = $_dir.$this->linkpath;
       return $this->linkpath;
    }
    //移动文件
    private function moveUpload() {
       if (is_uploaded_file($this->tmp)) {
         if (!move_uploaded_file($this->tmp,$this->setNewName())) {
            Tool::alertBack('警告:上传失败!');
         }
       } else {
         Tool::alertBack('警告:临时文件不存在!');
       }
    }
    //设置新文件名
    private function setNewName() {
       $_nameArr = explode('.',$this->name);
       $_postfix = $_nameArr[count($_nameArr)-1];
       $_newname = date('YmdHis').mt_rand(100,1000).'.'.$_postfix;
       $this->linkpath = UPDIR.$this->linktotay.$_newname;
       return $this->today.$_newname;
    }
    //验证目录
    private function checkPath() {
       if (!is_dir($this->path) || !is_writeable($this->path)) {
         if (!mkdir($this->path)) {
            Tool::alertBack('警告:主目录创建失败!');
         }
       }
       if (!is_dir($this->today) || !is_writeable($this->today)) {
         if (!mkdir($this->today)) {
            Tool::alertBack('警告:子目录创建失败!');
         }
       }
    }
    //验证类型
    private function checkType() {
       if (!in_array($this->type,$this->typeArr)) {
         Tool::alertBack('警告:不合法的上传类型!');
       }
    }
    //验证错误
    private function checkError() {
       if (!empty($this->error)) {
         switch ($this->error) {
            case 1 :
              Tool::alertBack('警告:上传值超过了约定最大值!');
              break;
            case 2 :
              Tool::alertBack('警告:上传值超过了'.$this->maxsize.'KB!');
              break;
            case 3 :
              Tool::alertBack('警告:只有部分文件被上传!');
              break;
            case 4 :
              Tool::alertBack('警告:没有任何文件被上传!');
              break;
            default:
              Tool::alertBack('警告:未知错误!');
         }
       }
    }
  }
?>

其中,用到了一个静态工具类 Tool.class.php,代码如下:

Tool.class.php

<?php
  class Tool {
     //弹窗返回
     static public function alertBack($_info) {
       echo "<script type='text/javascript'>alert('$_info');history.back();</script>";
       exit();
     }     //弹窗赋值关闭
     static public function alertOpenerClose($_info,$_path) {
       echo "<script type='text/javascript'>alert('$_info');</script>";
       echo "<script type='text/javascript'>opener.document.content.thumbnail.value='$_path';</script>";
       echo "<script type='text/javascript'>opener.document.content.pic.style.display='block';</script>";
       echo "<script type='text/javascript'>opener.document.content.pic.src='$_path';</script>";
       echo "<script type='text/javascript'>window.close();</script>";
       exit();
     } }
?>

下面进行一个实例演示,请看下面的步骤:

1、先创建一个 index.php 页面,做一个表单

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a target=_blank href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" rel="external nofollow" rel="external nofollow" >http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">
<html xmlns="<a target=_blank href="http://www.w3.org/1999/xhtml" rel="external nofollow" rel="external nofollow" >http://www.w3.org/1999/xhtml</a>">
  <head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <title>main</title>
  </head>
  <body>
     <form name="content" method="post" action="?action=add">
     <input type="text" name="thumbnail" class="text" readonly="readonly" /> <input type="button" value="上传" onclick="centerWindow('./upfile.html','upfile','400','100')" /> <img name="pic" style="display:none;" /> ( * 必须是jpg,gif,png,并且200k内) <br />
     </form>
  </body>
</html>

2、创建 upfile.html 文件,建立表单提交到 upload.php.

upfile.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a target=_blank href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" rel="external nofollow" rel="external nofollow" >http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">
<html xmlns="<a target=_blank href="http://www.w3.org/1999/xhtml" rel="external nofollow" rel="external nofollow" >http://www.w3.org/1999/xhtml</a>">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>上传图片</title>
  </head>
  <body></p><p>   <form method="post" action="./upload.php" enctype="multipart/form-data" style="text-align:center;margin:30px;">
    <input type="hidden" name="MAX_FILE_SIZE" value="204800" />
    <input type="file" name="pic" />
    <input type="submit" name="send" value="确定上传" />
</form></p><p></body>
</html>

3、通过 upload.php 文件调用文件上传类实现上传,并且把路径赋给 input 标签和显示图片

<?php
  require 'FileUpload.class.php';
  if (isset($_POST['send'])) {
    $_fileupload = new FileUpload('pic',$_POST['MAX_FILE_SIZE']);
    $_path = $_fileupload->getPath();
    Tool::alertOpenerClose('文件上传成功!',$_path);
  } else {
    Tool::alertBack('警告:文件过大或者其他未知错误导致浏览器崩溃!');
  }
?>

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
php中批量替换文件名的实现代码
Jul 20 PHP
PHP面向对象法则
Feb 23 PHP
解析PHP中的正则表达式以及模式匹配
Jun 19 PHP
多个PHP中文字符串截取函数
Nov 12 PHP
php中的curl使用入门教程和常见用法实例
Apr 10 PHP
ThinkPHP中pathinfo的访问模式、路径访问模式及URL重写总结
Aug 23 PHP
ThinkPHP框架设计及扩展详解
Nov 25 PHP
PHP学习笔记(一):基本语法之标记、空白、和注释
Apr 17 PHP
ThinkPHP开发框架函数详解:C方法
Aug 14 PHP
8个必备的PHP功能开发
Oct 02 PHP
阿里云PHP SMS短信服务验证码发送方法
Jul 11 PHP
如何通过View::first使用Laravel Blade的动态模板详解
Sep 21 PHP
PHP基于GD库实现的生成图片缩略图函数示例
Jul 05 #PHP
PHP实现的下载远程文件类定义与用法示例
Jul 05 #PHP
详解PHP使用Redis存储session时的一个Warning定位
Jul 05 #PHP
php如何修改SESSION的生存存储时间的实例代码
Jul 05 #PHP
PHP实现根据密码长度显示安全条
Jul 04 #PHP
PHP截取发动短信内容的方法
Jul 04 #PHP
phpcms配置列表页以及获得文章发布时间
Jul 04 #PHP
You might like
php数组函数序列之array_keys() - 获取数组键名
2011/10/30 PHP
php数组函数序列之array_flip() 将数组键名与值对调
2011/11/07 PHP
PHP fopen()和 file_get_contents()应用与差异介绍
2014/03/19 PHP
php使用GD2绘制几何图形示例
2017/02/15 PHP
zShowBox 图片放大展示jquery版 兼容性
2011/09/24 Javascript
javascript:;与javascript:void(0)使用介绍
2013/06/05 Javascript
JsRender实用入门教程
2014/10/31 Javascript
JS+CSS实现感应鼠标渐变显示DIV层的方法
2015/02/20 Javascript
Bootstrap项目实战之子栏目资讯内容
2016/04/25 Javascript
jQuery Mobile页面返回不需要重新get
2016/04/26 Javascript
基于jquery实现弹幕效果
2016/09/29 Javascript
基于Bootstrap的网页设计实例
2017/03/01 Javascript
利用jquery正则表达式在页面验证url网址输入是否正确
2017/04/04 jQuery
nodeJS实现简单网页爬虫功能的实例(分享)
2017/06/08 NodeJs
vue上传图片组件编写代码
2017/07/26 Javascript
JS获取并处理php数组的方法实例分析
2018/09/04 Javascript
新手快速入门微信小程序组件库 iView Weapp
2019/06/24 Javascript
在layui中select更改后生效的方法
2019/09/05 Javascript
nodejs如何在package.json中设置多条启动命令
2020/03/16 NodeJs
JavaScript字符和ASCII实现互相转换
2020/06/03 Javascript
python时间整形转标准格式的示例分享
2014/02/14 Python
Android模拟器无法启动,报错:Cannot set up guest memory ‘android_arm’ Invalid argument的解决方法
2016/07/01 Python
python+selenium实现163邮箱自动登陆的方法
2017/12/31 Python
Python+Pandas 获取数据库并加入DataFrame的实例
2018/07/25 Python
对python Tkinter Text的用法详解
2018/10/11 Python
学习python的前途 python挣钱
2019/02/27 Python
解决pycharm 工具栏Tool中找不到Run manager.py Task的问题
2019/07/01 Python
用Pytorch训练CNN(数据集MNIST,使用GPU的方法)
2019/08/19 Python
Python生成随机验证码代码实例解析
2020/06/09 Python
Lampenwelt德国:欧洲领先的灯具和照明在线商店
2018/08/05 全球购物
Haglöfs瑞典官方网站:haglofs火柴棍,欧洲顶级户外品牌
2018/10/18 全球购物
PREMIUM-MALL法国:行李、箱包及配件在线
2019/05/30 全球购物
销售业务员岗位职责
2014/01/29 职场文书
商务专员岗位职责范本
2014/06/29 职场文书
国家领导干部党的群众路线教育实践活动批评与自我批评材料
2014/09/23 职场文书
idea下配置tomcat避坑详解
2022/04/12 Servers