功能简介:
支持多图上传并生成缩略图
可自定义缩略图数量与尺寸
文件默认保存在 “./data/attachment/photo/年月/日/” 目录下
访问地址:http://localhost/upload/photo
如有问题请各位大侠海涵并指正,谢谢~
效果:
首先新建一个控制器文件,命名为:uploadcontroller.class.php,
位置:application\home\controller\uploadcontroller.class.php
控制器代码: 2097152,
'exts' => array('jpg', 'jpeg', 'png', 'gif'),
'rootpath' => $basedir,
'savepath' => $attachdir,
'subname' => array('date', 'd'),
'savename' => $savename,
'hash' => false
);
//初始化上传类
$upload = new \think\upload($config);
//检查是否选择图片
$inputname = 'photo';
$total = 0;
$data = array();
foreach($_files[$inputname] as $key => $value) {
foreach($value as $k => $v) {
$data[$k][$key] = $v;
if($key == 'name' && $v) {
$total++;
}
}
}
if(!$total) {
$this->error('请先选择要上传的图片!');
}
$uploadsuccess = $uploadfailure = 0;
$result = array();
//缩略图列表,数组为空则不生成缩略图
//键为缩略图文件名后缀,例如:20140221abc_a.jpg
//值为缩略图宽/高
$thumblist = array(
'a' => array(150, 150),
'c' => array(250, 250),
'm' => array(500, 500)
);
//初始化缩略图类
if(!empty($thumblist)) {
$image = new \think\image();
}
foreach($data as $key => $value) {
if(!$value['name']) continue;
//如果多图则从第二张开始设置新的文件名
if($key >= 1) {
$upload->savename = date('his').strtolower(random(16));
}
//开始上传
$file = $upload->upload(array($inputname => $value));
//上传成功
if(!empty($file)) {
$uploadsuccess++;
//缩略图
if(!empty($thumblist)) {
$path = $basedir.$file[$inputname]['savepath'].$upload->savename;
$fileext = $file[$inputname]['ext'];
$filepath = $path.'.'.$fileext;
//生成缩略图,按照原图的比例
foreach($thumblist as $thumbname => $thumbsize) {
if(!$thumbname || empty($thumbsize)) continue;
$image->open($filepath);
$image->thumb($thumbsize[0], $thumbsize[1])->save($path.'_'.$thumbname.'.'.$fileext);
}
}
} else {
$uploadfailure++;
}
$result[] = array($upload->geterror(), $file);
}
//成功提示
if($uploadsuccess) {
$this->success($uploadsuccess.'张图片上传成功!');
} else {
$this->error('上传失败!');
}
} else {
$value = array(
'meta_title' => '上传照片'
);
$this->assign($value)->display();
}
}
}html代码:
图片1:
图片2:
图片3:
确定上传
ad:真正免费,域名+虚机+企业邮箱=0元
