单文件上传与多文件上传的文件上传类

1、单文件上传

form.html

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="100000000">
    <input type="file" name="spic"> <br>

    <input type="submit" name="sub" value="upload file"><br>

</form>

upload.php

require "FileUpload.class.php";

    $up=new FileUpload(array(‘isRandName‘=>true,‘allowType‘=>array(‘jpg‘, ‘doc‘, ‘php‘, ‘gif‘),‘FilePath‘=>‘./uploads/‘, ‘MAXSIZE‘=>200000000));

    echo ‘<pre>‘;

    if($up->uploadFile(‘spic‘)){
        print_r($up->getNewFileName());
    }else{
        print_r($up->getErrorMsg());
    }

    echo ‘</pre>‘;

FileUpload.class.php

class FileUpload {
        private $filepath;     //指定上传文件保存的路径
        private $allowtype=array(‘gif‘, ‘jpg‘, ‘png‘, ‘jpeg‘);  //充许上传文件的类型
        private $maxsize=1000000;  //允上传文件的最大长度 1M
        private $israndname=true;  //是否随机重命名, true false不随机,使用原文件名
        private $originName;   //源文件名称
        private $tmpFileName;   //临时文件名
        private $fileType;  //文件类型
        private $fileSize;  //文件大小
        private $newFileName; //新文件名
        private $errorNum=0;  //错误号
        private $errorMess=""; //用来提供错误报告

        //用于对上传文件初使化
        //1. 指定上传路径, 2,充许的类型, 3,限制大小, 4,是否使用随机文件名称
        //让用户可以不用按位置传参数,后面参数给值不用将前几个参数也提供值
        function __construct($options=array()){
            foreach($options as $key=>$val){
                $key=strtolower($key);
                //查看用户参数中数组的下标是否和成员属性名相同
                if(!in_array($key,get_class_vars(get_class($this)))){
                    continue;
                }

                $this->setOption($key, $val);
            }

        }

        private function getError(){
            $str="上传文件<font color=‘red‘>{$this->originName}</font>时出错:";

            switch($this->errorNum){
                case 4: $str .= "没有文件被上传"; break;
                case 3: $str .= "文件只被部分上传"; break;
                case 2: $str .= "上传文件超过了HTML表单中MAX_FILE_SIZE选项指定的值"; break;
                case 1: $str .= "上传文件超过了php.ini 中upload_max_filesize选项的值"; break;
                case -1: $str .= "末充许的类型"; break;
                case -2: $str .= "文件过大,上传文件不能超过{$this->maxSize}个字节"; break;
                case -3: $str .= "上传失败"; break;
                case -4: $str .= "建立存放上传文件目录失败,请重新指定上传目录"; break;
                case -5: $str .= "必须指定上传文件的路径"; break;

                default: $str .=  "末知错误";
            }

            return $str.‘<br>‘;
        }

        //用来检查文件上传路径
        private function checkFilePath(){
            if(empty($this->filepath)) {
                $this->setOption(‘errorNum‘, -5);
                return false;
            }

            if(!file_exists($this->filepath) || !is_writable($this->filepath)){
                if([email protected]mkdir($this->filepath, 0755)){
                    $this->setOption(‘errorNum‘, -4);
                    return false;
                }
            }
            return true;
        }
        //用来检查文件上传的大小
        private function checkFileSize() {
            if($this->fileSize > $this->maxsize){
                $this->setOPtion(‘errorNum‘, ‘-2‘);
                return false;
            }else{
                return true;
            }
        }

        //用于检查文件上传类型
        private function checkFileType() {
            if(in_array(strtolower($this->fileType), $this->allowtype)) {
                return true;
            }else{
                $this->setOption(‘errorNum‘, -1);
                return false;
            }
        }
        //设置上传后的文件名称
        private function setNewFileName(){
            if($this->israndname){
                $this->setOption(‘newFileName‘, $this->proRandName());
            } else {
                $this->setOption(‘newFileName‘, $this->originName);
            }
        }

        //设置随机文件名称
        private function proRandName(){
            $fileName=date("YmdHis").rand(100,999);
            return $fileName.‘.‘.$this->fileType;
        }

        private function setOption($key, $val){
            $this->$key=$val;
        }
        //用来上传一个文件
        function uploadFile($fileField){
            $return=true;
            //检查文件上传路径
            if(!$this->checkFilePath()){
                $this->errorMess=$this->getError();
                return false;
            }

            $name=$_FILES[$fileField][‘name‘];
            $tmp_name=$_FILES[$fileField][‘tmp_name‘];
            $size=$_FILES[$fileField][‘size‘];
            $error=$_FILES[$fileField][‘error‘];

                    if($this->setFiles($name, $tmp_name, $size, $error)){
                        if($this->checkFileSize() && $this->checkFileType()){
                            $this->setNewFileName();

                            if($this->copyFile()){
                                return true;
                            }else{
                                $return=false;
                            }

                        }else{
                            $return=false;
                        }
                    }else{
                        $return=false;
                    }

                    if(!$return)
                        $this->errorMess=$this->getError();

                    return $return;

        }

        private function copyFile(){
            if(!$this->errorNum){
                $filepath=rtrim($this->filepath, ‘/‘).‘/‘;
                $filepath.=$this->newFileName;

                if(@move_uploaded_file($this->tmpFileName, $filepath))    {
                    return true;
                }else{
                    $this->setOption(‘errorNum‘, -3);
                    return false;
                }

            }else{
                return false;
            }
        }

        //设置和$_FILES有关的内容
        private function setFiles($name="", $tmp_name=‘‘, $size=0, $error=0){

            $this->setOption(‘errorNum‘, $error);

            if($error){
                return false;
            }

            $this->setOption(‘originName‘, $name);
            $this->setOption(‘tmpFileName‘, $tmp_name);
            $arrStr=explode(‘.‘, $name);
            $this->setOption(‘fileType‘, strtolower($arrStr[count($arrStr)-1]));
            $this->setOption(‘fileSize‘, $size);    

            return true;
        }    

        //用于获取上传后文件的文件名
        function getNewFileName(){
            return $this->newFileName;
        }
        //上传如果失败,则调用这个方法,就可以查看错误报告
        function getErrorMsg() {
            return $this->errorMess;
        }
    }

2、多文件上传

form.html

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="100000000">
    <input type="file" name="spic[]"> <br>
    <input type="file" name="spic[]"> <br>
    <input type="file" name="spic[]"> <br>
    <input type="file" name="spic[]"> <br>

    <input type="submit" name="sub" value="upload file"><br>

</form>

upload.php

require "FileUpload.class.php";

    $up=new FileUpload(array(‘isRandName‘=>true,‘allowType‘=>array(‘jpg‘, ‘doc‘, ‘php‘, ‘gif‘),‘FilePath‘=>‘./uploads/‘, ‘MAXSIZE‘=>200000000));

    echo ‘<pre>‘;

    if($up->uploadFile(‘spic‘)){
        print_r($up->getNewFileName());
    }else{
        print_r($up->getErrorMsg());
    }

    echo ‘</pre>‘;

FileUpload.class.php

class FileUpload {
        private $filepath;     //指定上传文件保存的路径
        private $allowtype=array(‘gif‘, ‘jpg‘, ‘png‘, ‘jpeg‘);  //充许上传文件的类型
        private $maxsize=1000000;  //允上传文件的最大长度 1M
        private $israndname=true;  //是否随机重命名, true false不随机,使用原文件名
        private $originName;   //源文件名称
        private $tmpFileName;   //临时文件名
        private $fileType;  //文件类型
        private $fileSize;  //文件大小
        private $newFileName; //新文件名
        private $errorNum=0;  //错误号
        private $errorMess=""; //用来提供错误报告

        //用于对上传文件初使化
        //1. 指定上传路径, 2,充许的类型, 3,限制大小, 4,是否使用随机文件名称
        //让用户可以不用按位置传参数,后面参数给值不用将前几个参数也提供值
        function __construct($options=array()){
            foreach($options as $key=>$val){
                $key=strtolower($key);
                //查看用户参数中数组的下标是否和成员属性名相同
                if(!in_array($key,get_class_vars(get_class($this)))){
                    continue;
                }

                $this->setOption($key, $val);
            }

        }

        private function getError(){
            $str="上传文件<font color=‘red‘>{$this->originName}</font>时出错:";

            switch($this->errorNum){
                case 4: $str .= "没有文件被上传"; break;
                case 3: $str .= "文件只被部分上传"; break;
                case 2: $str .= "上传文件超过了HTML表单中MAX_FILE_SIZE选项指定的值"; break;
                case 1: $str .= "上传文件超过了php.ini 中upload_max_filesize选项的值"; break;
                case -1: $str .= "末充许的类型"; break;
                case -2: $str .= "文件过大,上传文件不能超过{$this->maxSize}个字节"; break;
                case -3: $str .= "上传失败"; break;
                case -4: $str .= "建立存放上传文件目录失败,请重新指定上传目录"; break;
                case -5: $str .= "必须指定上传文件的路径"; break;

                default: $str .=  "末知错误";
            }

            return $str.‘<br>‘;
        }

        //用来检查文件上传路径
        private function checkFilePath(){
            if(empty($this->filepath)) {
                $this->setOption(‘errorNum‘, -5);
                return false;
            }

            if(!file_exists($this->filepath) || !is_writable($this->filepath)){
                if([email protected]mkdir($this->filepath, 0755)){
                    $this->setOption(‘errorNum‘, -4);
                    return false;
                }
            }
            return true;
        }
        //用来检查文件上传的大小
        private function checkFileSize() {
            if($this->fileSize > $this->maxsize){
                $this->setOPtion(‘errorNum‘, ‘-2‘);
                return false;
            }else{
                return true;
            }
        }

        //用于检查文件上传类型
        private function checkFileType() {
            if(in_array(strtolower($this->fileType), $this->allowtype)) {
                return true;
            }else{
                $this->setOption(‘errorNum‘, -1);
                return false;
            }
        }
        //设置上传后的文件名称
        private function setNewFileName(){
            if($this->israndname){
                $this->setOption(‘newFileName‘, $this->proRandName());
            } else {
                $this->setOption(‘newFileName‘, $this->originName);
            }
        }

        //设置随机文件名称
        private function proRandName(){
            $fileName=date("YmdHis").rand(100,999);
            return $fileName.‘.‘.$this->fileType;
        }

        private function setOption($key, $val){
            $this->$key=$val;
        }
        //用来上传一个文件
        function uploadFile($fileField){
            $return=true;
            //检查文件上传路径
            if(!$this->checkFilePath()){
                $this->errorMess=$this->getError();
                return false;
            }

            $name=$_FILES[$fileField][‘name‘];
            $tmp_name=$_FILES[$fileField][‘tmp_name‘];
            $size=$_FILES[$fileField][‘size‘];
            $error=$_FILES[$fileField][‘error‘];

            if(is_Array($name)){
                $errors=array();

                for($i=0; $i<count($name); $i++){
                    if($this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i])){
                        if(!$this->checkFileSize() || !$this->checkFileType()){
                            $errors[]=$this->getError();
                            $return=false;
                        }
                    }else{
                        $error[]=$this->getError();
                        $return=false;
                    }

                    if(!$return)
                        $this->setFiles();
                }

                if($return){
                    $fileNames=array();

                    for($i=0; $i<count($name); $i++){
                        if($this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i])){
                            $this->setNewFileName();
                            if(!$this->copyFile()){
                                $errors=$this->getError();
                                $return=false;
                            }else{
                                $fileNames[]=$this->newFileName;
                            }
                        }
                    }

                    $this->newFileName=$fileNames;
                }

                $this->errorMess=$errors;
                return $return;
            } else {

                    if($this->setFiles($name, $tmp_name, $size, $error)){
                        if($this->checkFileSize() && $this->checkFileType()){
                            $this->setNewFileName();

                            if($this->copyFile()){
                                return true;
                            }else{
                                $return=false;
                            }

                        }else{
                            $return=false;
                        }
                    }else{
                        $return=false;
                    }

                    if(!$return)
                        $this->errorMess=$this->getError();

                    return $return;
            }
        }

        private function copyFile(){
            if(!$this->errorNum){
                $filepath=rtrim($this->filepath, ‘/‘).‘/‘;
                $filepath.=$this->newFileName;

                if(@move_uploaded_file($this->tmpFileName, $filepath))    {
                    return true;
                }else{
                    $this->setOption(‘errorNum‘, -3);
                    return false;
                }

            }else{
                return false;
            }
        }

        //设置和$_FILES有关的内容
        private function setFiles($name="", $tmp_name=‘‘, $size=0, $error=0){

            $this->setOption(‘errorNum‘, $error);

            if($error){
                return false;
            }

            $this->setOption(‘originName‘, $name);
            $this->setOption(‘tmpFileName‘, $tmp_name);
            $arrStr=explode(‘.‘, $name);
            $this->setOption(‘fileType‘, strtolower($arrStr[count($arrStr)-1]));
            $this->setOption(‘fileSize‘, $size);    

            return true;
        }    

        //用于获取上传后文件的文件名
        function getNewFileName(){
            return $this->newFileName;
        }
        //上传如果失败,则调用这个方法,就可以查看错误报告
        function getErrorMsg() {
            return $this->errorMess;
        }
    }
时间: 2024-08-25 10:41:47

单文件上传与多文件上传的文件上传类的相关文章

[转]ExtJs入门之filefield:文件上传的配置+结合Ajax完美实现文件上传的asp.net示例

原文地址:http://www.stepday.com/topic/?459 作文一个ExtJs的入门汉子,学习起来的确是比较费劲的事情,不过如今在这样一个网络资源如此丰富的时代,依然不是那么难了的.基本上都是Copy过来加以部分改造即可实现自己想要的功能,加之如今的第三方开发者也大发慈悲地写出了API的帮助文档以及示例文档.关于ExtJs内的文件上传,将从以下几个方面进行展开讲解: 一.ExtJs文件上传版面的布局以及配置 因为ExtJs的文件上传组件filefield是基于form表单提交数

(转)Spring文件上传,包括一次选中多个文件

背景: http://www.cnblogs.com/lixuwu/p/8495275.html已经实现了单文件的上传和下载,多文件的上传是另一种情景,这里记录下来 实现过程 先说前台. 运行以后就是这样子的. 一个非常简单的表单页面, 两个文件上传按钮, 一个提交 其中单个文件上传, 即只能选择一个文件, 无法同时选择多个 相对的, 多个文件就是可以同时选择多个文件了 文件选择以后就是这个样子 前台设置 代码如下: 一个form, 文件上传就是一个<input>输入, 属性type=&quo

git 上传代码到GitHub 以及git删除github上文件和文件的命令

Git入门 如果你完全没有接触过Git,你现在只需要理解通过Git的语法(敲入一些命令)就可以将代码上传到远程的仓库或者下载到本地的仓库(服务器),可知我们此时应该有两个仓库,就是两个放代码的地方,一个是本地,一个是远程的(如Github).企业或者团队可以通过Git来对项目进行管理,每个程序员只需将自己的本地仓库写好的代码上传到远程仓库,另一个程序员就可以下载到本地仓库了.今天我们就从Git终端软件的安装开始,再这之前我也简单介绍一下Github. Git上传代码 一.准备工作 1.注册一个g

webDAV服务的开启以及客户端的上传、下载、删除、新建文件夾、列表的代码(C#)

windows server 2003开启webDAV服务 1. 启动“IIS管理器”选择“WEB服务扩展”,选择“WEBDAV”的允许按钮启动WEBDAV功能 2.建立一个虚拟目录,对应到一个本地目录. 3.启动系统“服务”中的“WebClient”服务 参考网址 WebDAV文档rfc2518    http://www.ietf.org/rfc/rfc2518.txt webdav常用方法和概念总结   http://blog.csdn.net/mahongming/archive/200

js上传文件带参数,并且,返回给前台文件路径,解析上传的xml文件,存储到数据库中

ajaxfileupload.js jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '&qu

改变FileUpload文件上传控件的显示方式,确认后上传

一.Aspx页面: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUploadDemo.aspx.cs" Inherits="WebApplication1.FileUploadDemo" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN&qu

Excel文件上传,解析,下载(一 文件上传,使用MultipartFile来实现)

文件上传我使用的是jquery的一个插件"ajaxfileupload.js",使用方式详见下面的一种方式,使用file类型的input,同时需要给button绑定事件,这边使用的"ajaxfileupload.js"当中定义的ajax请求,到后台. <div id="fileupload"> <input type="file" id="file" name="file&quo

selenium -文件上传的实现 -对于含有input element的上传

一.对于上传文件, 从手动操作我们可以看出, 需要对window 窗体进行操作, 而对于selenium webdriver 在这方面应用就受到了限制. 但是, 庆幸的是, 对于含有input element的上传, 我们可以直接通过sendkeys来传入文件路径,省略了对window 窗体的操作来实现文件上传, 具体实现过程如下: 1)找到上传控件element,并输入路径: WebElement element = driver.findElement(By.id("cloudFax-att

jQuery.uploadify-----文件上传带进度条,支持多文件上传的插件

借鉴别人总结的uploadify:基于jquery的文件上传插件,支持ajax无刷新上传,多个文件同时上传,上传进行进度显示,控制文件上传大小,删除已上传文件. uploadify有两个版本,一个用flash,一个是html5.html5的需要付费~所以这里只说flash版本的用法. uploadify官网地址:http://www.uploadify.com/ 上传文件截图: uploadify文档:http://www.uploadify.com/documentation/,在这儿可以查看

史上最全的maven的pom.xml文件详解

史上最全的maven的pom.xml文件详解 http://www.cnblogs.com/hafiz/p/5360195.html <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 h