thinkphp3.2.2有预览的多图上传
thinkphp3.2.2有预览的多图上传
整体思路
1 封装文件上传和图片上传的类文件
2 视图中添加相关JS和表单提交
3 控制器中添加上传文件的相关代码
一 2个class 文件 请上传到/ThinkPHP/Library/Think/
UploadFile.class.php
<?php
namespace Think;
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: UploadFile.class.php 2568 2012-01-10 12:15:45Z liu21st $ /**
+------------------------------------------------------------------------------
* 文件上传类
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Net
* @author liu21st <liu21st@gmail.com>
* @version $Id: UploadFile.class.php 2568 2012-01-10 12:15:45Z liu21st $
+------------------------------------------------------------------------------
*/
class UploadFile {//类定义开始 // 上传文件的最大值
public $maxSize = -1; // 是否支持多文件上传
public $supportMulti = true; // 允许上传的文件后缀
// 留空不作后缀检查
public $allowExts = array(); // 允许上传的文件类型
// 留空不做检查
public $allowTypes = array(); // 使用对上传图片进行缩略图处理
public $thumb = false;
// 图库类包路径
public $imageClassPath = 'Think.UploadImage';
// 缩略图最大宽度
public $thumbMaxWidth;
// 缩略图最大高度
public $thumbMaxHeight;
// 缩略图前缀
public $thumbPrefix = 'thumb_';
public $thumbSuffix = '';
// 缩略图保存路径
public $thumbPath = '';
// 缩略图文件名
public $thumbFile = '';
// 是否移除原图
public $thumbRemoveOrigin = false;
// 压缩图片文件上传
public $zipImages = false;
// 启用子目录保存文件
public $autoSub = false;
// 子目录创建方式 可以使用hash date
public $subType = 'hash';
public $dateFormat = 'Ymd';
public $hashLevel = 1; // hash的目录层次
// 上传文件保存路径
public $savePath = '';
public $autoCheck = true; // 是否自动检查附件
// 存在同名是否覆盖
public $uploadReplace = false; // 上传文件命名规则
// 例如可以是 time uniqid com_create_guid 等
// 必须是一个无需任何参数的函数名 可以使用自定义函数
public $saveRule = ''; // 上传文件Hash规则函数名
// 例如可以是 md5_file sha1_file 等
public $hashType = 'md5_file'; // 错误信息
private $error = ''; // 上传成功的文件信息
private $uploadFileInfo ; /**
+----------------------------------------------------------
* 架构函数
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($maxSize='',$allowExts='',$allowTypes='',$savePath='',$saveRule='') {
if(!empty($maxSize) && is_numeric($maxSize)) {
$this->maxSize = $maxSize;
}
if(!empty($allowExts)) {
if(is_array($allowExts)) {
$this->allowExts = array_map('strtolower',$allowExts);
}else {
$this->allowExts = explode(',',strtolower($allowExts));
}
}
if(!empty($allowTypes)) {
if(is_array($allowTypes)) {
$this->allowTypes = array_map('strtolower',$allowTypes);
}else {
$this->allowTypes = explode(',',strtolower($allowTypes));
}
}
if(!empty($saveRule)) {
$this->saveRule = $saveRule;
}else{
$this->saveRule = C('UPLOAD_FILE_RULE');
}
$this->savePath = $savePath;
} /**
+----------------------------------------------------------
* 上传一个文件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param mixed $name 数据
* @param string $value 数据表名
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
private function save($file) {
$filename = $file['savepath'].$file['savename'];
if(!$this->uploadReplace && is_file($filename)) {
// 不覆盖同名文件
$this->error = '文件已经存在!'.$filename;
return false;
}
// 如果是图像文件 检测文件格式
if( in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png','swf')) && false === getimagesize($file['tmp_name'])) {
$this->error = '非法图像文件';
return false;
}
if(!move_uploaded_file($file['tmp_name'], $this->autoCharset($filename,'utf-8','gbk'))) {
$this->error = '文件上传保存错误!';
return false;
}
if($this->thumb && in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png'))) {
$image = getimagesize($filename);
if(false !== $image) {
//是图像文件生成缩略图
$thumbWidth = explode(',',$this->thumbMaxWidth);
$thumbHeight = explode(',',$this->thumbMaxHeight);
$thumbPrefix = explode(',',$this->thumbPrefix);
$thumbSuffix = explode(',',$this->thumbSuffix);
$thumbFile = explode(',',$this->thumbFile);
$thumbPath = $this->thumbPath?$this->thumbPath:$file['savepath'];
// 生成图像缩略图
import($this->imageClassPath);
$realFilename = $this->autoSub?basename($file['savename']):$file['savename'];
for($i=0,$len=count($thumbWidth); $i<$len; $i++) {
$thumbname = $thumbPath.$thumbPrefix[$i].substr($realFilename,0,strrpos($realFilename, '.')).$thumbSuffix[$i].'.'.$file['extension'];
UploadImage::thumb($filename,$thumbname,'',$thumbWidth[$i],$thumbHeight[$i],true);
}
if($this->thumbRemoveOrigin) {
// 生成缩略图之后删除原图
unlink($filename);
}
}
}
if($this->zipImags) {
// TODO 对图片压缩包在线解压 }
return true;
} /**
+----------------------------------------------------------
* 上传所有文件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $savePath 上传文件保存路径
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function upload($savePath ='') {
//如果不指定保存文件名,则由系统默认
if(empty($savePath))
$savePath = $this->savePath;
// 检查上传目录
if(!is_dir($savePath)) {
// 检查目录是否编码后的
if(is_dir(base64_decode($savePath))) {
$savePath = base64_decode($savePath);
}else{
// 尝试创建目录
if(!mkdir($savePath)){
$this->error = '上传目录'.$savePath.'不存在';
return false;
}
}
}else {
if(!is_writeable($savePath)) {
$this->error = '上传目录'.$savePath.'不可写';
return false;
}
}
$fileInfo = array();
$isUpload = false; // 获取上传的文件信息
// 对$_FILES数组信息处理
$files = $this->dealFiles($_FILES);
foreach($files as $key => $file) {
//过滤无效的上传
if(!empty($file['name'])) {
//登记上传文件的扩展信息
$file['key'] = $key;
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file); // 自动检查附件
if($this->autoCheck) {
if(!$this->check($file))
return false;
} //保存上传文件
if(!$this->save($file)) return false;
if(function_exists($this->hashType)) {
$fun = $this->hashType;
$file['hash'] = $fun($this->autoCharset($file['savepath'].$file['savename'],'utf-8','gbk'));
}
//上传成功后保存文件信息,供其他地方调用
unset($file['tmp_name'],$file['error']);
$fileInfo[] = $file;
$isUpload = true;
}
}
if($isUpload) {
$this->uploadFileInfo = $fileInfo;
return true;
}else {
$this->error = '没有选择上传文件';
return false;
}
} //循环创建目录 lish 开放
/*function mk_dir($dir, $mode = 0755)
{
if (is_dir($dir) || @mkdir($dir,$mode)) return true;
if (!mk_dir(dirname($dir),$mode)) return false;
return @mkdir($dir,$mode);
} */ public function mk_dir($dir, $mode = 0755)
{
if (is_dir($dir) || @mkdir($dir,$mode,true)) return true;
if (!mk_dir(dirname($dir),$mode,true)) return false;
return @mkdir($dir,$mode,true);
}
/**
+----------------------------------------------------------
* 上传单个上传字段中的文件 支持多附件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param array $file 上传文件信息
* @param string $savePath 上传文件保存路径
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function uploadOne($file,$savePath=''){
//如果不指定保存文件名,则由系统默认
if(empty($savePath))
$savePath = $this->savePath;
// 检查上传目录
if(!is_dir($savePath)) {
// 尝试创建目录
if(!mk_dir($savePath)){
$this->error = '上传目录'.$savePath.'不存在';
return false;
}
}else {
if(!is_writeable($savePath)) {
$this->error = '上传目录'.$savePath.'不可写';
return false;
}
}
//过滤无效的上传
if(!empty($file['name'])) {
$fileArray = array();
if(is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i=0; $i<$count; $i++) {
foreach ($keys as $key)
$fileArray[$i][$key] = $file[$key][$i];
}
}else{
$fileArray[] = $file;
}
$info = array();
foreach ($fileArray as $key=>$file){
//登记上传文件的扩展信息
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
// 自动检查附件
if($this->autoCheck) {
if(!$this->check($file))
return false;
}
//保存上传文件
if(!$this->save($file)) return false;
if(function_exists($this->hashType)) {
$fun = $this->hashType;
$file['hash'] = $fun($this->autoCharset($file['savepath'].$file['savename'],'utf-8','gbk'));
}
unset($file['tmp_name'],$file['error']);
$info[] = $file;
}
// 返回上传的文件信息
return $info;
}else {
$this->error = '没有选择上传文件';
return false;
}
} /**
+----------------------------------------------------------
* 转换上传文件数组变量为正确的方式
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $files 上传的文件变量
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
private function dealFiles($files) {
$fileArray = array();
$n = 0;
foreach ($files as $file){
if(is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i=0; $i<$count; $i++) {
foreach ($keys as $key)
$fileArray[$n][$key] = $file[$key][$i];
$n++;
}
}else{
$fileArray[$n] = $file;
$n++;
}
}
return $fileArray;
} /**
+----------------------------------------------------------
* 获取错误代码信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $errorNo 错误号码
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
protected function error($errorNo) {
switch($errorNo) {
case 1:
$this->error = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
break;
case 2:
$this->error = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
break;
case 3:
$this->error = '文件只有部分被上传';
break;
case 4:
$this->error = '没有文件被上传';
break;
case 6:
$this->error = '找不到临时文件夹';
break;
case 7:
$this->error = '文件写入失败';
break;
default:
$this->error = '未知上传错误!';
}
return ;
} /**
+----------------------------------------------------------
* 根据上传文件命名规则取得保存文件名
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 数据
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function getSaveName($filename) {
$rule = $this->saveRule;
if(empty($rule)) {//没有定义命名规则,则保持文件名不变
$saveName = $filename['name'];
}else {
if(function_exists($rule)) {
//使用函数生成一个唯一文件标识号
$saveName = $rule().".".$filename['extension'];
}else {
//使用给定的文件名作为标识号
$saveName = $rule.".".$filename['extension'];
}
}
if($this->autoSub) {
// 使用子目录保存文件
$filename['savename'] = $saveName;
$saveName = $this->getSubName($filename).'/'.$saveName;
}
return $saveName;
} /**
+----------------------------------------------------------
* 获取子目录的名称
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $file 上传的文件信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function getSubName($file) {
switch($this->subType) {
case 'date':
$dir = date($this->dateFormat,time());
break;
case 'hash':
default:
$name = md5($file['savename']);
$dir = '';
for($i=0;$i<$this->hashLevel;$i++) {
$dir .= $name{$i}.'/';
}
break;
}
if(!is_dir($file['savepath'].$dir)) { //mk_dir($file['savepath'].$dir);
mkdir($file['savepath'].$dir,true); //自己改的 迎合php5.0 }
return $dir;
} /**
+----------------------------------------------------------
* 检查上传的文件
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $file 文件信息
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function check($file) {
if($file['error']!== 0) {
//文件上传失败
//捕获错误代码
$this->error($file['error']);
return false;
}
//文件上传成功,进行自定义规则检查
//检查文件大小
if(!$this->checkSize($file['size'])) {
$this->error = '上传文件大小不符!';
return false;
} //检查文件Mime类型
if(!$this->checkType($file['type'])) {
$this->error = '上传文件MIME类型不允许!';
return false;
}
//检查文件类型
if(!$this->checkExt($file['extension'])) {
$this->error ='上传文件类型不允许';
return false;
} //检查是否合法上传
if(!$this->checkUpload($file['tmp_name'])) {
$this->error = '非法上传文件!';
return false;
}
return true;
} // 自动转换字符集 支持数组转换
private function autoCharset($fContents, $from='gbk', $to='utf-8') {
$from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
$to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
//如果编码相同或者非字符串标量则不转换
return $fContents;
}
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($fContents, $to, $from);
} elseif (function_exists('iconv')) {
return iconv($from, $to, $fContents);
} else {
return $fContents;
}
} /**
+----------------------------------------------------------
* 检查上传的文件类型是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $type 数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkType($type) {
if(!empty($this->allowTypes))
return in_array(strtolower($type),$this->allowTypes);
return true;
} /**
+----------------------------------------------------------
* 检查上传的文件后缀是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $ext 后缀名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkExt($ext) {
if(!empty($this->allowExts))
return in_array(strtolower($ext),$this->allowExts,true);
return true;
} /**
+----------------------------------------------------------
* 检查文件大小是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param integer $size 数据
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkSize($size) {
return !($size > $this->maxSize) || (-1 == $this->maxSize);
} /**
+----------------------------------------------------------
* 检查文件是否非法提交
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 文件名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkUpload($filename) {
return is_uploaded_file($filename);
} /**
+----------------------------------------------------------
* 取得上传文件的后缀
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 文件名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function getExt($filename) {
$pathinfo = pathinfo($filename);
return $pathinfo['extension'];
} /**
+----------------------------------------------------------
* 取得上传文件的信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getUploadFileInfo() {
return $this->uploadFileInfo;
} /**
+----------------------------------------------------------
* 取得最后一次错误信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getErrorMsg() {
return $this->error;
} }
2 UploadImage.class.php
<?php
namespace Think; // +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Image.class.php 2708 2012-02-06 04:10:11Z liu21st $ /**
+------------------------------------------------------------------------------
* 图像操作类库
+------------------------------------------------------------------------------
* @category ORG
* @package ORG
* @subpackage Util
* @author liu21st <liu21st@gmail.com>
* @version $Id: Image.class.php 2708 2012-02-06 04:10:11Z liu21st $
+------------------------------------------------------------------------------
*/
class UploadImage { /**
+----------------------------------------------------------
* 取得图像信息
*
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $image 图像文件名
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/ static function getImageInfo($img) {
$imageInfo = getimagesize($img);
if ($imageInfo !== false) {
$imageType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
$imageSize = filesize($img);
$info = array(
"width" => $imageInfo[0],
"height" => $imageInfo[1],
"type" => $imageType,
"size" => $imageSize,
"mime" => $imageInfo['mime']
);
return $info;
} else {
return false;
}
} /**
+----------------------------------------------------------
* 为图片添加水印
+----------------------------------------------------------
* @static public
+----------------------------------------------------------
* @param string $source 原文件名
* @param string $water 水印图片
* @param string $$savename 添加水印后的图片名
* @param string $alpha 水印的透明度
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static public function water($source, $water, $savename=null, $alpha=80) {
//检查文件是否存在
if (!file_exists($source) || !file_exists($water))
return false; //图片信息
$sInfo = self::getImageInfo($source);
$wInfo = self::getImageInfo($water); //如果图片小于水印图片,不生成图片
if ($sInfo["width"] < $wInfo["width"] || $sInfo['height'] < $wInfo['height'])
return false; //建立图像
$sCreateFun = "imagecreatefrom" . $sInfo['type'];
$sImage = $sCreateFun($source);
$wCreateFun = "imagecreatefrom" . $wInfo['type'];
$wImage = $wCreateFun($water); //设定图像的混色模式
imagealphablending($wImage, true); //图像位置,默认为右下角右对齐
$posY = $sInfo["height"] - $wInfo["height"];
$posX = $sInfo["width"] - $wInfo["width"]; //生成混合图像
imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo['width'], $wInfo['height'], $alpha); //输出图像
$ImageFun = 'Image' . $sInfo['type'];
//如果没有给出保存文件名,默认为原图像名
if (!$savename) {
$savename = $source;
@unlink($source);
}
//保存图像
$ImageFun($sImage, $savename);
imagedestroy($sImage);
} function showImg($imgFile, $text='', $x='10', $y='10', $alpha='50') {
//获取图像文件信息
//2007/6/26 增加图片水印输出,$text为图片的完整路径即可
$info = UploadImage::getImageInfo($imgFile);
if ($info !== false) {
$createFun = str_replace('/', 'createfrom', $info['mime']);
$im = $createFun($imgFile);
if ($im) {
$ImageFun = str_replace('/', '', $info['mime']);
//水印开始
if (!empty($text)) {
$tc = imagecolorallocate($im, 0, 0, 0);
if (is_file($text) && file_exists($text)) {//判断$text是否是图片路径
// 取得水印信息
$textInfo = Image::getImageInfo($text);
$createFun2 = str_replace('/', 'createfrom', $textInfo['mime']);
$waterMark = $createFun2($text);
//$waterMark=imagecolorallocatealpha($text,255,255,0,50);
$imgW = $info["width"];
$imgH = $info["width"] * $textInfo["height"] / $textInfo["width"];
//$y = ($info["height"]-$textInfo["height"])/2;
//设置水印的显示位置和透明度支持各种图片格式
imagecopymerge($im, $waterMark, $x, $y, 0, 0, $textInfo['width'], $textInfo['height'], $alpha);
} else {
imagestring($im, 80, $x, $y, $text, $tc);
}
//ImageDestroy($tc);
}
//水印结束
if ($info['type'] == 'png' || $info['type'] == 'gif') {
imagealphablending($im, FALSE); //取消默认的混色模式
imagesavealpha($im, TRUE); //设定保存完整的 alpha 通道信息
}
Header("Content-type: " . $info['mime']);
$ImageFun($im);
@ImageDestroy($im);
return;
} //保存图像
$ImageFun($sImage, $savename);
imagedestroy($sImage);
//获取或者创建图像文件失败则生成空白PNG图片
$im = imagecreatetruecolor(80, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
imagestring($im, 4, 5, 5, "no pic", $tc);
UploadImage::output($im);
return;
}
} /**
+----------------------------------------------------------
* 生成缩略图
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $image 原图
* @param string $type 图像格式
* @param string $thumbname 缩略图文件名
* @param string $maxWidth 宽度
* @param string $maxHeight 高度
* @param string $position 缩略图保存目录
* @param boolean $interlace 启用隔行扫描
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
static function thumb($image, $thumbname, $type='', $maxWidth=200, $maxHeight=50, $interlace=true) {
// 获取原图信息
$info = UploadImage::getImageInfo($image);
if ($info !== false) {
$srcWidth = $info['width'];
$srcHeight = $info['height'];
$type = empty($type) ? $info['type'] : $type;
$type = strtolower($type);
$interlace = $interlace ? 1 : 0;
unset($info);
$scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); // 计算缩放比例
if ($scale >= 1) {
// 超过原图大小不再缩略
$width = $srcWidth;
$height = $srcHeight;
} else {
// 缩略图尺寸
$width = (int) ($srcWidth * $scale);
$height = (int) ($srcHeight * $scale);
} // 载入原图
$createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
$srcImg = $createFun($image); //创建缩略图
if ($type != 'gif' && function_exists('imagecreatetruecolor'))
$thumbImg = imagecreatetruecolor($width, $height);
else
$thumbImg = imagecreate($width, $height); // 复制图片
if (function_exists("ImageCopyResampled"))
imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
else
imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
if ('gif' == $type || 'png' == $type) {
//imagealphablending($thumbImg, false);//取消默认的混色模式
//imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息
$background_color = imagecolorallocate($thumbImg, 0, 255, 0); // 指派一个绿色
imagecolortransparent($thumbImg, $background_color); // 设置为透明色,若注释掉该行则输出绿色的图
} // 对jpeg图形设置隔行扫描
if ('jpg' == $type || 'jpeg' == $type)
imageinterlace($thumbImg, $interlace); // 生成图片
$imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type);
$imageFun($thumbImg, $thumbname);
imagedestroy($thumbImg);
imagedestroy($srcImg);
return $thumbname;
}
return false;
} /**
+----------------------------------------------------------
* 把图像转换成字符显示
+----------------------------------------------------------
* @static
* @access public
+----------------------------------------------------------
* @param string $image 要显示的图像
* @param string $type 图像类型,默认自动获取
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function showASCIIImg($image, $string='', $type='') {
$info = Image::getImageInfo($image);
if ($info !== false) {
$type = empty($type) ? $info['type'] : $type;
unset($info);
// 载入原图
$createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
$im = $createFun($image);
$dx = imagesx($im);
$dy = imagesy($im);
$i = 0;
$out = '<span style="padding:0px;margin:0;line-height:100%;font-size:1px;">';
set_time_limit(0);
for ($y = 0; $y < $dy; $y++) {
for ($x = 0; $x < $dx; $x++) {
$col = imagecolorat($im, $x, $y);
$rgb = imagecolorsforindex($im, $col);
$str = empty($string) ? '*' : $string[$i++];
$out .= sprintf('<span style="margin:0px;color:#%02x%02x%02x">' . $str . '</span>', $rgb['red'], $rgb['green'], $rgb['blue']);
}
$out .= "<br>\n";
}
$out .= '</span>';
imagedestroy($im);
return $out;
}
return false;
} /**
+----------------------------------------------------------
* 生成UPC-A条形码
+----------------------------------------------------------
* @static
+----------------------------------------------------------
* @param string $type 图像格式
* @param string $type 图像格式
* @param string $lw 单元宽度
* @param string $hi 条码高度
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
static function UPCA($code, $type='png', $lw=2, $hi=100) {
static $Lencode = array('0001101', '0011001', '0010011', '0111101', '0100011',
'0110001', '0101111', '0111011', '0110111', '0001011');
static $Rencode = array('1110010', '1100110', '1101100', '1000010', '1011100',
'1001110', '1010000', '1000100', '1001000', '1110100');
$ends = '101';
$center = '01010';
/* UPC-A Must be 11 digits, we compute the checksum. */
if (strlen($code) != 11) {
die("UPC-A Must be 11 digits.");
}
/* Compute the EAN-13 Checksum digit */
$ncode = '0' . $code;
$even = 0;
$odd = 0;
for ($x = 0; $x < 12; $x++) {
if ($x % 2) {
$odd += $ncode[$x];
} else {
$even += $ncode[$x];
}
}
$code.= ( 10 - (($odd * 3 + $even) % 10)) % 10;
/* Create the bar encoding using a binary string */
$bars = $ends;
$bars.=$Lencode[$code[0]];
for ($x = 1; $x < 6; $x++) {
$bars.=$Lencode[$code[$x]];
}
$bars.=$center;
for ($x = 6; $x < 12; $x++) {
$bars.=$Rencode[$code[$x]];
}
$bars.=$ends;
/* Generate the Barcode Image */
if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
$im = imagecreatetruecolor($lw * 95 + 30, $hi + 30);
} else {
$im = imagecreate($lw * 95 + 30, $hi + 30);
}
$fg = ImageColorAllocate($im, 0, 0, 0);
$bg = ImageColorAllocate($im, 255, 255, 255);
ImageFilledRectangle($im, 0, 0, $lw * 95 + 30, $hi + 30, $bg);
$shift = 10;
for ($x = 0; $x < strlen($bars); $x++) {
if (($x < 10) || ($x >= 45 && $x < 50) || ($x >= 85)) {
$sh = 10;
} else {
$sh = 0;
}
if ($bars[$x] == '1') {
$color = $fg;
} else {
$color = $bg;
}
ImageFilledRectangle($im, ($x * $lw) + 15, 5, ($x + 1) * $lw + 14, $hi + 5 + $sh, $color);
}
/* Add the Human Readable Label */
ImageString($im, 4, 5, $hi - 5, $code[0], $fg);
for ($x = 0; $x < 5; $x++) {
ImageString($im, 5, $lw * (13 + $x * 6) + 15, $hi + 5, $code[$x + 1], $fg);
ImageString($im, 5, $lw * (53 + $x * 6) + 15, $hi + 5, $code[$x + 6], $fg);
}
ImageString($im, 4, $lw * 95 + 17, $hi - 5, $code[11], $fg);
/* Output the Header and Content. */
Image::output($im, $type);
} static function output($im, $type='png', $filename='') {
header("Content-type: image/" . $type);
$ImageFun = 'image' . $type;
if (empty($filename)) {
$ImageFun($im);
} else {
$ImageFun($im, $filename);
}
imagedestroy($im);
} }
第二步 视图中增加简单代码
我的测试代码放在这里 /Application/Home/View/Index/index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>多图片上传预览(原创)-jq22.com</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
img {
vertical-align: top;
width:500px;
}</style>
</head>
<body>
<form enctype="multipart/form-data" action="__URL__/upload" method="post"> <input id="browse" name="photo[]" type="file" onchange="previewFiles()" multiple="">
<div id="preview"></div>
<input type="submit" value="提交">
</form>
</body>
</html> <script>
function previewFiles() { var preview = document.querySelector('#preview');
var files = document.querySelector('input[type=file]').files; function readAndPreview(file) { // Make sure `file.name` matches our extensions criteria
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
var reader = new FileReader(); reader.addEventListener("load", function() {
var image = new Image();
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
}, false); reader.readAsDataURL(file);
} } if (files) {
[].forEach.call(files, readAndPreview);
} }
</script> </body>
</html>
第3 控制器的上传代码
/Application/Home/Controller/IndexController.class.php
<?php
namespace Home\Controller;
use Think\Controller; class IndexController extends Controller {
public function upload()
{
$upload = new \Think\UploadFile();// 实例化上传类
$upload->maxSize = 3000000 ;// 设置附件上传大小 C('UPLOAD_SIZE');
$upload->savePath = './Uploads/' . 'thumb/'; // 设置附件上传目录
$upload->allowExts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
$upload->saveRule = 'uniqid';
$upload->uploadReplace = true; //是否存在同名文件是否覆盖 $upload->thumb = true; //是否对上传文件进行缩略图处理
$upload->thumbMaxWidth = '300,600'; //缩略图处理宽度
$upload->thumbMaxHeight = '200,400'; //缩略图处理高度
$upload->thumbPrefix = 'm_,s_'; //生产2张缩略图
$upload->thumbPath = './Uploads/' . 'thumb/' . date('Ymd', time()) . '/'; //缩略图保存路径 $upload->thumbRemoveOrigin = true; //上传图片后删除原图片
$upload->autoSub = true; //是否使用子目录保存图片
$upload->subType = 'date'; //子目录保存规则
$upload->dateFormat = 'Ymd'; //子目录保存规则为date时时间格式 if(!$upload->upload()){// 上传错误提示错误信息
$this->error($upload->getError());
} else {
$info = $upload->getUploadFileInfo(); foreach($info as $file)
{
/*$model = M( 'web_img');
$picname = $file['savename'];
$picname = explode('/', $picname);
$url1 = $picname[0] . '/' . 'm_' . $picname[1];
$url2 = $picname[0] . '/' . 's_' . $picname[1];
$temp["face"] = $file['savepath'].$url2; //大缩略图
$temp["thumb"] = $file['savepath'].$url1; //小缩略图
$temp["Addtime"] = date("Y/m/d H:i:s");
//$save=$model->add($temp);
* */
$save=1;
}
if($save){
$this->success('上传成功!');
}
} }
}
最后看下效果
thinkphp3.2.2有预览的多图上传的更多相关文章
- 基于HTML5的可预览多图片Ajax上传
一.关于图片上传什么什么的 在XHTML的时代,我们使用HTML file控件上传图片一次只能上传一张.要一次上传多图,做法是借助于flash.例如swfupload.js.可惜,使用复杂的点,比如f ...
- ASP.NET工作笔记之一:图片上传预览及无刷新上传
转自:http://www.cnblogs.com/sibiyellow/archive/2012/04/27/jqueryformjs.html 最近项目里面涉及到无刷新上传图片的功能,其实也就是上 ...
- HTML5可预览多图片ajax上传(使用formData传递数据)
HTML5可预览多图片ajax上传(使用formData传递数据) 在介绍上传图片之前,我们简单的来了解下FormData的基本使用:介绍完成后这些基本知识后,我们会在文章最后提供一个demo,就是a ...
- html选择图片后预览,保存并上传
html代码:------------------添加-------------------------- accept="image/gif,image/jpeg,image/jpg,im ...
- HTML5预览图片、异步上传文件
注意啦:本文的代码都是以JQuery为示例,jq_开头的变量都是jq对象. 在HTML5中,我们可以在图片上传之前对图片进行预览,就像下面这么做 jq_upload_file.change(funct ...
- .net core版 文件上传/ 支持批量上传,拖拽以及预览,bootstrap fileinput上传文件
asp.net mvc请移步 mvc文件上传支持批量上传,拖拽以及预览,文件内容校验 本篇内容主要解决.net core中文件上传的问题 开发环境:ubuntu+vscode 1.导入所需要的包:n ...
- ASP.NET MVC 一款可预览、裁剪头像上传组件
今天介绍一款Web上常用的头像上传组件,常用于头像上传时对用户上传的图片进行裁剪并实时预览,最终效果如下: 源代码结构: Github地址: https://github.com/FrankFan/A ...
- H5图片预览、压缩、上传
目标实现: 1.选择图片, 前端预览效果 2.图片大于1.2M的时候, 对图片进行压缩 3.以表单的形式上传图片 4.图片删除 预览效果图: 代码说明: 1.input:file选择图片 <!- ...
- vue富文本编辑,编辑自动预览,单个图片上传不能预览的问题解决:
//预览<div class="htmlViewBox"> <p v-html="activity_html_defaultMsg" v-sh ...
随机推荐
- 2015.4.21第一篇cnblog文章
个人学习记录第一篇. 输出才是最好一条途径,这也是开源的精神所在.
- 获取 TUniConnection.SpecificOptions默认值和下拉框列表值
TUniConnection的SpecificOptions参数决定了数据库连接配置参数,但可惜的是,SpecificOptions设计器界面,Devart公司只能让它在设计期配置! Specific ...
- Winfrom窗体无法关闭问题--检查是否存在重写
问题描述: Winfrom窗体无法关闭问题----点击关闭/最大/最小化无法正常相应. 问题来源: 老版本的程序要求使用无边框的Form窗体(实现功能——设置为无边框窗体并重写窗体的关闭.最大.最小化 ...
- 在MacOSX系统上的一些工具和问题汇总
Android 模拟器 1. 安装模拟器 点击链接:https://cloud.genymotion.com/page/launchpad/download 需要先注册登录一下. 2.安装Virtua ...
- String[]字符串数组,按字典顺序排列大小
package ltb6w1; public class WordSort1 { private String[] a= {"hello","world",&q ...
- WARNING: Package of target [javax.servlet.jsp.jstl.core.LoopTagSupport$1Status@7439e436] or package of member [public int javax.servlet.jsp.jstl.core.LoopTagSupport$1Status.getIndex()] are excluded!
Struts2爆出045漏洞后,将struts版本升级到了2.3.32.但是在验证时发现有些jstl循环未出现预期的结果. debug发现,数据没有问题,断定是前端页面显示出了问题.根据日志信息WAR ...
- P1258小车问题
传送 很多人质疑它是二分,但其实它就是二分(我会说我不会解方程吗) 据说有很多人没看懂题干在说些什么,那就不要管题干了.拿样例算一遍,我们看看样例的答案是怎么算出来的. 这是样例.看到这个数,我们很懵 ...
- 若是汉字的一半,就舍弃这个汉字输出,例如:“js3范ad啊asd”,截取4,则输出:“js3”
package com.jt.test.redis; import org.junit.Test; /* 题目要求 * 编码:GBK,一个英文字符占一个字节,一个汉字占2个字节 * 随机给定一个字符串 ...
- go语言学习--map类型的切片
今天在项目中遇到了一个切片的map,记录下map切片的使用 package main import "fmt" func main() { // Version A: items ...
- KPPW2.5 漏洞利用--SQL注入
KPPW2.5 漏洞利用--SQL注入 SQL注入--布尔型盲注 环境搭建 1,集成环境简单方便,如wamp,phpstudy.... 2,KPPW v2.2源码一份(文末有分享)放到WWW目录下面 ...