====================ImageUploadTool========================

<?php

class ImageUploadTool
{
private $file; //文件信息
private $fileList; //文件列表
private $inputName; //标签名称
private $uploadPath; //上传路径
private $fileMaxSize; //最大尺寸
private $uploadFiles; //上传文件
//允许上传的文件类型
private $allowExt = array('bmp', 'jpg', 'jpeg', 'png', 'gif'); /**
* ImageUploadTool constructor.
* @param $inputName input标签的name属性
* @param $uploadPath 文件上传路径
*/
public function __construct($inputName, $uploadPath)
{
$this->inputName = $inputName;
$this->uploadPath = $uploadPath;
$this->fileList = array();
$this->file = $file = array(
'name' => null,
'type' => null,
'tmp_name' => null,
'size' => null,
'errno' => null,
'error' => null
);
} /**
* 设置允许上传的图片后缀格式
* @param $allowExt 文件后缀数组
*/
public function setAllowExt($allowExt)
{
if (is_array($allowExt)) {
$this->allowExt = $allowExt;
} else {
$this->allowExt = array($allowExt);
}
} /**
* 设置允许上传的图片规格
* @param $fileMaxSize 最大文件尺寸
*/
public function setMaxSize($fileMaxSize)
{
$this->fileMaxSize = $fileMaxSize;
} /**
* 获取上传成功的文件数组
* @return mixed
*/
public function getUploadFiles()
{
return $this->uploadFiles;
} /**
* 得到文件上传的错误信息
* @return array|mixed
*/
public function getErrorMsg()
{
if (count($this->fileList) == 0) {
return $this->file['error'];
} else {
$errArr = array();
foreach ($this->fileList as $item) {
array_push($errArr, $item['error']);
}
return $errArr;
}
} /**
* 初始化文件参数
* @param $isList
*/
private function initFile($isList)
{
if ($isList) {
foreach ($_FILES[$this->inputName] as $key => $item) {
for ($i = 0; $i < count($item); $i++) {
if ($key == 'error') {
$this->fileList[$i]['error'] = null;
$this->fileList[$i]['errno'] = $item[$i];
} else {
$this->fileList[$i][$key] = $item[$i];
}
}
}
} else {
$this->file['name'] = $_FILES[$this->inputName]['name'];
$this->file['type'] = $_FILES[$this->inputName]['type'];
$this->file['tmp_name'] = $_FILES[$this->inputName]['tmp_name'];
$this->file['size'] = $_FILES[$this->inputName]['size'];
$this->file['errno'] = $_FILES[$this->inputName]['error'];
}
} /**
* 上传错误检查
* @param $errno
* @return null|string
*/
private function errorCheck($errno)
{
switch ($errno) {
case UPLOAD_ERR_OK:
return null;
case UPLOAD_ERR_INI_SIZE:
return '文件尺寸超过服务器限制';
case UPLOAD_ERR_FORM_SIZE:
return '文件尺寸超过表单限制';
case UPLOAD_ERR_PARTIAL:
return '只有部分文件被上传';
case UPLOAD_ERR_NO_FILE:
return '没有文件被上传';
case UPLOAD_ERR_NO_TMP_DIR:
return '找不到临时文件夹';
case UPLOAD_ERR_CANT_WRITE:
return '文件写入失败';
case UPLOAD_ERR_EXTENSION:
return '上传被扩展程序中断';
}
} /**
* 上传文件校验
* @param $file
* @throws Exception
*/
private function fileCheck($file)
{
//图片上传过程是否顺利
if ($file['errno'] != 0) {
$error = $this->errorCheck($file['errno']);
throw new Exception($error);
}
//图片尺寸是否符合要求
if (!empty($this->fileMaxSize) && $file['size'] > $this->fileMaxSize) {
throw new Exception('文件尺寸超过' . ($this->fileMaxSize / 1024) . 'KB');
}
//图片类型是否符合要求
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
if (!in_array($ext, $this->allowExt)) {
throw new Exception('不符合要求的文件类型');
}
//图片上传方式是否为HTTP
if (!is_uploaded_file($file['tmp_name'])) {
throw new Exception('文件不是通过HTTP方式上传的');
}
//图片是否可以读取
if (!getimagesize($file['tmp_name'])) {
throw new Exception('图片文件损坏');
}
//检查上传路径是否存在
if (!file_exists($this->uploadPath)) {
mkdir($this->uploadPath, null, true);
}
} /**
* 单文件上传,成功返回true
* @return bool
*/
public function acceptSingleFile()
{
$this->initFile(false);
try {
$this->fileCheck($this->file);
$md_name = md5(uniqid(microtime(true), true)) . '.' . pathinfo($this->file['name'], PATHINFO_EXTENSION);
if (move_uploaded_file($this->file['tmp_name'], $this->uploadPath . $md_name)) {
$this->uploadFiles = array($this->uploadPath . $md_name);
} else {
throw new Exception('文件上传失败');
}
} catch (Exception $e) {
$this->file['error'] = $e->getMessage();
} finally {
if (file_exists($this->file['tmp_name'])) {
unlink($this->file['tmp_name']);
}
}
return empty($this->file['error']) ? true : false;
} /**
* 多文件上传,全部成功返回true
* @return bool
*/
public function acceptMultiFile()
{
$this->initFile(true);
$this->uploadFiles = array();
for ($i = 0; $i < count($this->fileList); $i++) {
try {
$this->fileCheck($this->fileList[$i]);
$ext = pathinfo($this->fileList[$i]['name'], PATHINFO_EXTENSION);
$md_name = md5(uniqid(microtime(true), true)) . '.' . $ext;
if (move_uploaded_file($this->fileList[$i]['tmp_name'], $this->uploadPath . $md_name)) {
array_push($this->uploadFiles, $this->uploadPath . $md_name);
} else {
throw new Exception('文件上传失败');
}
} catch (Exception $e) {
$this->fileList[$i]['error'] = $e->getMessage();
} finally {
if (file_exists($this->fileList[$i]['tmp_name'])) {
unlink($this->fileList[$i]['tmp_name']);
}
}
}
foreach ($this->fileList as $item) {
if (!empty($item['error'])) {
return false;
}
}
return true;
}
}

ImageUploadTool.class.php

=======================单文件上传===========================

首先创建一个简单HTML表单:

<form action="tool_test.php" method="post" enctype="multipart/form-data">
<!--通过表单隐藏域限制上传文件的最大值-->
<!--<input type="hidden" name="MAX_FILE_SIZE" value="204800">-->
<!--通过accept属性限制上传文件类型-->
<!--<input type="hidden" name="myfile" accept="image/jpeg,image/png">--> <label for="upload">请选择上传的文件</label>
<input type="file" id="upload" name="myfile"><br>
<input type="submit" value="上传文件">
</form>

再创建一个tool_test.php文件:

<?php
//引用图片上传工具
require_once 'ImageUploadTool.class.php'; //初始化上传工具,参数(input表单name属性 , 文件上传路径)
$uploadTool = new ImageUploadTool('myfile', 'file/'); //进行单文件上传操作,上传成功返回true
if ($uploadTool->acceptSingleFile()) { //获取上传后的文件路径,并用img标签显示
echo "<img src='{$uploadTool->getUploadFiles()[0]}'/>"; } else { //打印错误信息
echo $uploadTool->getErrorMsg(); }

=======================文件上传===========================

首先创建一个简单HTML表单:

需要在<input type="file">标签的name属性后面追加“[]”,并且添加 multiple 属性

<form action="tool_test.php" method="post" enctype="multipart/form-data">
<label for="upload">请选择上传的文件</label>
<input type="file" id="upload" name="myfile[]" multiple><br>
<input type="submit" value="上传文件">
</form>

再创建一个tool_test.php文件:

<?php
//引用图片上传工具
require_once 'ImageUploadTool.class.php'; //初始化上传工具,参数(input表单name属性 , 文件上传路径)
$uploadTool = new ImageUploadTool('myfile', 'file/'); //设置允许上传的文件后缀类型
$uploadTool->setAllowExt(array('png', 'jpg')); //设置上传文件的最大尺寸
$uploadTool->setMaxSize(1024 * 200); //进行多文件上传操作,全部上传成功返回true
$uploadTool->acceptMultiFile(); //打印所有上传成功的图片路径
print_r($uploadTool->getUploadFiles()); //打印所有上传失败的错误信息
print_r($uploadTool->getErrorMsg());

多文件上传测试:

PHP 图片上传工具类(支持多文件上传)的更多相关文章

  1. Jquery图片上传组件,支持多文件上传

    Jquery图片上传组件,支持多文件上传http://www.jq22.com/jquery-info230jQuery File Upload 是一个Jquery图片上传组件,支持多文件上传.取消. ...

  2. ajaxfileupload多文件上传 - 修复只支持单个文件上传的bug

    搜索: jquery ajaxFileUpload AjaxFileUpload同时上传多个文件 原生的AjaxFileUpload插件是不支持多文件上传的,通过修改AjaxFileUpload少量代 ...

  3. spring mvc 文件上传工具类

    虽然文件上传在框架中,已经不是什么困难的事情了,但自己还是开发了一个文件上传工具类,是基于springmvc文件上传的. 工具类只需要传入需要的两个参数,就可以上传到任何想要上传的路径: 参数1:Ht ...

  4. spring boot 文件上传工具类(bug 已修改)

    以前的文件上传都是之前前辈写的,现在自己来写一个,大家可以看看,有什么问题可以在评论中提出来. 写的这个文件上传是在spring boot 2.0中测试的,测试了,可以正常上传,下面贴代码 第一步:引 ...

  5. 文件上传工具类 UploadUtil.java

    package com.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...

  6. 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)

    前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上 ...

  7. FastDFS 文件上传工具类

    FastDFS文件上传工具类 import org.csource.common.NameValuePair; import org.csource.fastdfs.ClientGlobal; imp ...

  8. php 图片上传 并返回上传文件位置 支持多文件上传

    <?php /** * Created by PhpStorm. * User: DY040 * Date: 2018/4/26 * Time: 13:23 */ echo '<pre&g ...

  9. 表单多文件上传样式美化 && 支持选中文件后删除相关项

    开发中会经常涉及到文件上传的需求,根据业务不同的需求,有不同的文件上传情况. 有简单的单文件上传,有多文件上传,因浏览器原生的文件上传样式及功能的支持度不算太高,很多时候我们会对样式进行美化,对功能进 ...

  10. Android开发调试日志工具类[支持保存到SD卡]

    直接上代码: package com.example.callstatus; import java.io.File; import java.io.FileWriter; import java.i ...

随机推荐

  1. js封装的三级联动菜单(使用时只需要一行js代码)

    前言 在实际的项目开发中,我们经常需要三级联动,比如省市区的选择,商品的三级分类的选择等等. 而网上却找不到一个代码完整.功能强大.使用简单的三级联动菜单,大都只是简单的讲了一下实现思路. 下面就给大 ...

  2. 基于C/S架构的3D对战网络游戏C++框架 _05搭建系统开发环境与Boost智能指针、内存池初步了解

    本系列博客主要是以对战游戏为背景介绍3D对战网络游戏常用的开发技术以及C++高级编程技巧,有了这些知识,就可以开发出中小型游戏项目或3D工业仿真项目. 笔者将分为以下三个部分向大家介绍(每日更新): ...

  3. .NET跨平台之旅:基于.NET Core改写EnyimMemcached,实现Linux上访问memcached缓存

    注:支持 .NET Core 的 memcached 客户端 EnyimMemcachedCore 的 NuGet 包下载地址:https://www.nuget.org/packages/Enyim ...

  4. 2-SAT

      n个布尔变量,满足m个如 A为x或B为y的限制 建一个点拆成两个,分别表示选TRUE或FALSE 建立A的!x B的y 的连边 与 A的x B的!y 的连边 每次dfs. 若一个点在之前条件下无论 ...

  5. HDU3068 回文串 Manacher算法

    好久没有刷题了,虽然参加过ACM,但是始终没有融会贯通,没有学个彻底.我干啥都是半吊子,一瓶子不满半瓶子晃荡. 就连简单的Manacher算法我也没有刷过,常常为岁月蹉跎而感到后悔. 问题描述 给定一 ...

  6. jquery版固定边栏滚动特效

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>& ...

  7. Jenkins创建Maven项目及SSH部署

    前面我们已经安装了Jenkins的环境,以及配置好了jdk和maven.下面我们来看如何通过Jenkins将svn的项目进行打包和部署. 创建MAVEN项目 1.点击新建,输入项目名,选择" ...

  8. SSH框架的简单上传功能的实现

    1.创建项目. 2.导入开发包. 3.配置web.xml. 配置内容就是配置struct2的内容如下: <?xml version="1.0" encoding=" ...

  9. Socket编程(4)TCP粘包问题及解决方案

    ① TCP是个流协议,它存在粘包问题 TCP是一个基于字节流的传输服务,"流"意味着TCP所传输的数据是没有边界的.这不同于UDP提供基于消息的传输服务,其传输的数据是有边界的.T ...

  10. project.pbxproj 的merge问题

    基于xcode8.0 1.project.pbxproj 的结构 内部文件{archiveVersion=1 ; classes={};objectVersion=46;objects={};root ...