多文件上传是PHP中的一个基础应用,反正PHPer都会遇到的问题,现在就介绍一个功能完善、强大的多文件上传类给大家吧,能用上这个类的地方会很多。

<?php

class Upload{
var $saveName;// 保存名
var $savePath;// 保存路径
var $fileFormat = array('gif','jpg','doc','application/octet-stream');// 文件格式&MIME限定
var $overwrite = 0;// 覆盖模式
var $maxSize = 0;// 文件最大字节
var $ext;// 文件扩展名
var $thumb = 0;// 是否生成缩略图
var $thumbWidth = 130;// 缩略图宽
var $thumbHeight = 130;// 缩略图高
var $thumbPrefix = "_thumb_";// 缩略图前缀
var $errno;// 错误代号
var $returnArray= array();// 所有文件的返回信息
var $returninfo= array();// 每个文件返回信息 // 构造函数
// @param $savePath 文件保存路径
// @param $fileFormat 文件格式限制数组
// @param $maxSize 文件最大尺寸
// @param $overwriet 是否覆盖 1 允许覆盖 0 禁止覆盖 function Upload($savePath, $fileFormat='',$maxSize = 0, $overwrite = 0) {
$this->setSavepath($savePath);
$this->setFileformat($fileFormat);
$this->setMaxsize($maxSize);
$this->setOverwrite($overwrite);
$this->setThumb($this->thumb, $this->thumbWidth,$this->thumbHeight);
$this->errno = 0;
} // 上传
// @param $fileInput 网页Form(表单)中input的名称
// @param $changeName 是否更改文件名
function run($fileInput,$changeName = 1){
if(isset($_FILES[$fileInput])){
$fileArr = $_FILES[$fileInput];
if(is_array($fileArr['name'])){//上传同文件域名称多个文件
for($i = 0; $i < count($fileArr['name']); $i++){
$ar['tmp_name'] = $fileArr['tmp_name'][$i];
$ar['name'] = $fileArr['name'][$i];
$ar['type'] = $fileArr['type'][$i];
$ar['size'] = $fileArr['size'][$i];
$ar['error'] = $fileArr['error'][$i];
$this->getExt($ar['name']);//取得扩展名,赋给$this->ext,下次循环会更新
$this->setSavename($changeName == 1 ? '' : $ar['name']);//设置保存文件名
if($this->copyfile($ar)){
$this->returnArray[] = $this->returninfo;
}else{
$this->returninfo['error'] = $this->errmsg();
$this->returnArray[] = $this->returninfo;
}
}
return $this->errno ? false : true;
}else{//上传单个文件
$this->getExt($fileArr['name']);//取得扩展名
$this->setSavename($changeName == 1 ? '' : $fileArr['name']);//设置保存文件名
if($this->copyfile($fileArr)){
$this->returnArray[] = $this->returninfo;
}else{
$this->returninfo['error'] = $this->errmsg();
$this->returnArray[] = $this->returninfo;
}
return $this->errno ? false : true;
}
return false;
}else{
$this->errno = 10;
return false;
}
} // 单个文件上传
// @param $fileArray 文件信息数组
function copyfile($fileArray){
$this->returninfo = array();
// 返回信息
$this->returninfo['name'] = $fileArray['name'];
$this->returninfo['md5'] = @md5_file($fileArray['tmp_name']);
$this->returninfo['saveName'] = $this->saveName;
$this->returninfo['size'] = number_format( ($fileArray['size'])/1024 , 0, '.', ' ');//以KB为单位
$this->returninfo['type'] = $fileArray['type'];
// 检查文件格式
if (!$this->validateFormat()){
$this->errno = 11;
return false;
}
// 检查目录是否可写
if(!@is_writable($this->savePath)){
$this->errno = 12;
return false;
}
// 如果不允许覆盖,检查文件是否已经存在
//if($this->overwrite == 0 && @file_exists($this->savePath.$fileArray['name'])){
// $this->errno = 13;
// return false;
//}
// 如果有大小限制,检查文件是否超过限制
if ($this->maxSize != 0 ){
if ($fileArray["size"] > $this->maxSize){
$this->errno = 14;
return false;
}
}
// 文件上传
if(!@move_uploaded_file($fileArray["tmp_name"], $this->savePath.$this->saveName)){
$this->errno = $fileArray["error"];
return false;
}elseif( $this->thumb ){// 创建缩略图
$CreateFunction = "imagecreatefrom".($this->ext == 'jpg' ? 'jpeg' : $this->ext);
$SaveFunction = "image".($this->ext == 'jpg' ? 'jpeg' : $this->ext);
if (strtolower($CreateFunction) == "imagecreatefromgif"
&& !function_exists("imagecreatefromgif")) {
$this->errno = 16;
return false;
} elseif (strtolower($CreateFunction) == "imagecreatefromjpeg"
&& !function_exists("imagecreatefromjpeg")) {
$this->errno = 17;
return false;
} elseif (!function_exists($CreateFunction)) {
$this->errno = 18;
return false;
} $Original = @$CreateFunction($this->savePath.$this->saveName);
if (!$Original) {$this->errno = 19; return false;}
$originalHeight = ImageSY($Original);
$originalWidth = ImageSX($Original);
$this->returninfo['originalHeight'] = $originalHeight;
$this->returninfo['originalWidth'] = $originalWidth;
/*
if (($originalHeight < $this->thumbHeight
&& $originalWidth < $this->thumbWidth)) {
// 如果比期望的缩略图小,那只Copy
move_uploaded_file($this->savePath.$this->saveName,
$this->savePath.$this->thumbPrefix.$this->saveName);
} else {
if( $originalWidth > $this->thumbWidth ){// 宽 > 设定宽度
$thumbWidth = $this->thumbWidth ;
$thumbHeight = $this->thumbWidth * ( $originalHeight / $originalWidth );
if($thumbHeight > $this->thumbHeight){// 高 > 设定高度
$thumbWidth = $this->thumbHeight * ( $thumbWidth / $thumbHeight );
$thumbHeight = $this->thumbHeight ;
}
}elseif( $originalHeight > $this->thumbHeight ){// 高 > 设定高度
$thumbHeight = $this->thumbHeight ;
$thumbWidth = $this->thumbHeight * ( $originalWidth / $originalHeight );
if($thumbWidth > $this->thumbWidth){// 宽 > 设定宽度
$thumbHeight = $this->thumbWidth * ( $thumbHeight / $thumbWidth );
$thumbWidth = $this->thumbWidth ;
}
}
*/
$radio=max(($originalWidth/$this->thumbWidth),($originalHeight/$this->thumbHeight));
$thumbWidth=(int)$originalWidth/$radio;
$thumbHeight=(int)$originalHeight/$radio; if ($thumbWidth == 0) $thumbWidth = 1;
if ($thumbHeight == 0) $thumbHeight = 1;
$createdThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
if ( !$createdThumb ) {$this->errno = 20; return false;}
if ( !imagecopyresampled($createdThumb, $Original, 0, 0, 0, 0,
$thumbWidth, $thumbHeight, $originalWidth, $originalHeight) )
{$this->errno = 21; return false;}
if ( !$SaveFunction($createdThumb,
$this->savePath.$this->thumbPrefix.$this->saveName) )
{$this->errno = 22; return false;} }
// 删除临时文件
/*
if(!@$this->del($fileArray["tmp_name"])){
return false;
}
*/
return true;
} // 文件格式检查,MIME检测
function validateFormat(){
if(!is_array($this->fileFormat)
|| in_array(strtolower($this->ext), $this->fileFormat)
|| in_array(strtolower($this->returninfo['type']), $this->fileFormat) )
return true;
else
return false;
}
// 获取文件扩展名
// @param $fileName 上传文件的原文件名
function getExt($fileName){
$ext = explode(".", $fileName);
$ext = $ext[count($ext) - 1];
$this->ext = strtolower($ext);
} // 设置上传文件的最大字节限制
// @param $maxSize 文件大小(bytes) 0:表示无限制
function setMaxsize($maxSize){
$this->maxSize = $maxSize;
}
// 设置文件格式限定
// @param $fileFormat 文件格式数组
function setFileformat($fileFormat){
if(is_array($fileFormat)){$this->fileFormat = $fileFormat ;}
} // 设置覆盖模式
// @param overwrite 覆盖模式 1:允许覆盖 0:禁止覆盖
function setOverwrite($overwrite){
$this->overwrite = $overwrite;
} // 设置保存路径
// @param $savePath 文件保存路径:以 "/" 结尾,若没有 "/",则补上
function setSavepath($savePath){
$this->savePath = substr( str_replace("\\","/", $savePath) , -1) == "/"
? $savePath : $savePath."/";
} // 设置缩略图
// @param $thumb = 1 产生缩略图 $thumbWidth,$thumbHeight 是缩略图的宽和高
function setThumb($thumb, $thumbWidth = 0,$thumbHeight = 0){
$this->thumb = $thumb;
if($thumbWidth) $this->thumbWidth = $thumbWidth;
if($thumbHeight) $this->thumbHeight = $thumbHeight;
} // 设置文件保存名
// @param $saveName 保存名,如果为空,则系统自动生成一个随机的文件名
function setSavename($saveName){
if ($saveName == ''){ // 如果未设置文件名,则生成一个随机文件名
$name = date('YmdHis')."_".rand(100,999).'.'.$this->ext;
//判断文件是否存在,不允许重复文件
if(file_exists($this->savePath . $name)){
$name = setSavename($saveName);
}
} else {
$name = $saveName;
}
$this->saveName = $name;
} // 删除文件
// @param $fileName 所要删除的文件名
function del($fileName){
if(!@unlink($fileName)){
$this->errno = 15;
return false;
}
return true;
} // 返回上传文件的信息
function getInfo(){
return $this->returnArray;
} // 得到错误信息
function errmsg(){
$uploadClassError = array(
0 =>'There is no error, the file uploaded with success. ',
1 =>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
2 =>'The uploaded file exceeds the MAX_FILE_SIZE that was specified in the HTML form.',
3 =>'The uploaded file was only partially uploaded. ',
4 =>'No file was uploaded. ',
6 =>'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3. ',
7 =>'Failed to write file to disk. Introduced in PHP 5.1.0. ',
10 =>'Input name is not unavailable!',
11 =>'The uploaded file is Unallowable!',
12 =>'Directory unwritable!',
13 =>'File exist already!',
14 =>'File is too big!',
15 =>'Delete file unsuccessfully!',
16 =>'Your version of PHP does not appear to have GIF thumbnailing support.',
17 =>'Your version of PHP does not appear to have JPEG thumbnailing support.',
18 =>'Your version of PHP does not appear to have pictures thumbnailing support.',
19 =>'An error occurred while attempting to copy the source image .
Your version of php ('.phpversion().') may not have this image type support.',
20 =>'An error occurred while attempting to create a new image.',
21 =>'An error occurred while copying the source image to the thumbnail image.',
22 =>'An error occurred while saving the thumbnail image to the filesystem.
Are you sure that PHP has been configured with both read and write access on this folder?',
);
if ($this->errno == 0)
return false;
else
return $uploadClassError[$this->errno];
}
} ?>

如何使用这个类呢?

<?php
//如果收到表单传来的参数,则进行上传处理,否则显示表单
if(isset($_FILES['uploadinput'])){
//建目录函数,其中参数$directoryName最后没有"/",
//要是有的话,以'/'打散为数组的时候,最后将会出现一个空值
function makeDirectory($directoryName) {
$directoryName = str_replace("\\","/",$directoryName);
$dirNames = explode('/', $directoryName);
$total = count($dirNames) ;
$temp = '';
for($i=0; $i<$total; $i++) {
$temp .= $dirNames[$i].'/';
if (!is_dir($temp)) {
$oldmask = umask(0);
if (!mkdir($temp, 0777)) exit("不能建立目录 $temp");
umask($oldmask);
}
}
return true;
} if($_FILES['uploadinput']['name'] <> ""){
//包含上传文件类
require_once ('upload_class.php');
//设置文件上传目录
$savePath = "upload";
//创建目录
makeDirectory($savePath);
//允许的文件类型
$fileFormat = array('gif','jpg','jpge','png');
//文件大小限制,单位: Byte,1KB = 1000 Byte
//0 表示无限制,但受php.ini中upload_max_filesize设置影响
$maxSize = 0;
//覆盖原有文件吗? 0 不允许 1 允许
$overwrite = 0;
//初始化上传类
$f = new Upload( $savePath, $fileFormat, $maxSize, $overwrite);
//如果想生成缩略图,则调用成员函数 $f->setThumb();
//参数列表: setThumb($thumb, $thumbWidth = 0,$thumbHeight = 0)
//$thumb=1 表示要生成缩略图,不调用时,其值为 0
//$thumbWidth 缩略图宽,单位是像素(px),留空则使用默认值 130
//$thumbHeight 缩略图高,单位是像素(px),留空则使用默认值 130
$f->setThumb(1); //参数中的uploadinput是表单中上传文件输入框input的名字
//后面的0表示不更改文件名,若为1,则由系统生成随机文件名
if (!$f->run('uploadinput',1)){
//通过$f->errmsg()只能得到最后一个出错的信息,
//详细的信息在$f->getInfo()中可以得到。
echo $f->errmsg()."<br>\n";
}
//上传结果保存在数组returnArray中。
echo "<pre>";
print_r($f->getInfo());
echo "</pre>";
}
}else{
?>
<form enctype="multipart/form-data" action="" method="POST">
Send this file: <br />
<input name="uploadinput[]" type="file"><br />
<input name="uploadinput[]" type="file"><br />
<input name="uploadinput[]" type="file"><br />
<input type="submit" value="Send File"><br />
</form>
<?php
} ?>

PHP多图片上传类推荐的更多相关文章

  1. [上传下载] C# ImageUpload图片上传类教程与源码下载 (转载)

    点击下载 ImageUpload.zip 功能如下图片1.设置属性后上传图片,用法如下 /// <summary> /// 图片上传类 /// </summary> //--- ...

  2. PHP图片上传类

    前言 在php开发中,必不可少要用到文件上传,整理封装了一个图片上传的类也很有必要. 图片上传的流程图 一.控制器调用 public function upload_file() { if (IS_P ...

  3. 阿里云OSS图片上传类

    1.阿里云基本函数 /** * 把本地变量的内容到文件 * 简单上传,上传指定变量的内存值作为object的内容 */ public function putObject($imgPath,$obje ...

  4. PHP之图片上传类(加了缩略图)

    有缩略图功能 但是 感觉不全面,而且有点问题,继续学习,将来以后修改下 <form action="<?php $_SERVER['PHP_SELF']; ?>" ...

  5. laravel之引入图片上传类

    1.在官网http://www.uploadify.com/ 下载插件,flash verison 的版本是免费版 2.解压后将文件夹放置在指定的目录下 3.前端导入css,js文件,可以仿照文件夹中 ...

  6. ASP.NET 图片上传工具类 upload image简单好用功能齐全

    使用方法: UploadImage ui = new UploadImage(); /***可选参数***/ ui.SetWordWater = "哈哈";//文字水印 // ui ...

  7. THINKPHP源码学习--------文件上传类

    TP图片上传类的理解 在做自己项目上传图片的时候一直都有用到TP的上传图片类,所以要进入源码探索一下. 文件目录:./THinkPHP/Library/Think/Upload.class.php n ...

  8. yii php 图片上传与生成缩略图

    今天需要做图片上传与生成缩略图的功能,把代码进行记录如下: html 视图              ($pic_action_url = $this->createAbsoluteUrl('h ...

  9. yii2.0 图片上传(摘录)

    文章来源:http://blog.sina.com.cn/s/blog_88a65c1b0101izmn.html 下面小伙就带领大学学习一下 Yii2.0 的图片上传类的使用,还是老样子,如果代码样 ...

随机推荐

  1. 编译android内核和文件系统,已经安装jdk,提示build/core/config.mk:268: *** Error: could not find jdk tools.jar

    1:确保安装jdk,如果没有安装请移布:http://www.cnblogs.com/jiuyueguang/p/3156621.html 2:如果已经安装了jdk,还是提示此错误, 解决方法 请确保 ...

  2. Silverlight中使用MVVM(3)

    Silverlight中使用MVVM(1)--基础 Silverlight中使用MVVM(2)—提高 Silverlight中使用MVVM(3)—进阶 Silverlight中使用MVVM(4)—演练 ...

  3. Oracle:exp导出exp-00091问题

    今天导出一数据库数据,发现EXP-00091问题: 连接到: Oracle Database 10g Enterprise Edition Release - Production With the ...

  4. 书写优雅的shell脚本(四) - kill命令的合理使用

    Linux中的kill命令用来终止指定的进程(terminate a process)的运行,是Linux下进程管理的常用命令.通常,终止一个前台进程可以使用Ctrl+C键,但是,对于一个后台进程就须 ...

  5. 51Nod 1717

    链接 分析:对于任意一个数,它的约数总是成对出现的,但是对于完全平方数,它因为有两个约数不相等,所以只会出现奇数次,所以最终的结果就是减去完全平方数 #include "iostream&q ...

  6. 【NOI 2015】软件包管理器

    [题目链接] 点击打开链接 [算法] 树链剖分,子树的DFS序也是连续的一段 要注意细节! [代码] #include<bits/stdc++.h> using namespace std ...

  7. C++ 动态多维数组的申请与释放

    今天在实验室的项目中遇到了一个问题,直接上代码: void ViBe::init(Mat img) { imgcol = img.cols; imgrow = img.rows; // 动态分配三维数 ...

  8. (二十八)分类信息的curd-分类信息删除

    删除分类步骤分析: 1.在list.jsp上编写 删除连接 /store/adminCategory?method=delete&cid=?? 2.在delete方法中 获取cid 调用ser ...

  9. ASP.NET Core MVC 2.x 全面教程_ASP.NET Core MVC 01. 创建项目 +项目结构和配置简介

    新建项目:Tutotial.Web 解决方案名称可以把web去掉 视频里面把git这个选项勾选了.我就不勾选了 dotnet CLI创建项目 首先必须安装好了.net Core的SDK dotnet ...

  10. 任务36:应用Jwtbearer Authentication

    任务36:应用Jwtbearer Authentication D:\MyDemos\jesse 新建项目:dotnet new webapi --name JwtAuthSample VS2017运 ...