首先下载uploadify插件,链接 http://www.uploadify.com/demos/
引入js库文件:jquery-3.1.1.min.js
引入uploadify核心js文件:jquery.uploadify.min.js
模板页面:index.html
$(function(){
$('#file_upload1').uploadify({
uploader:"{:U('Image/addProducts1')}", // 服务器处理地址
swf: '__PUBLIC__/uploadify/uploadify.swf',
buttonText: "图片替换", //按钮文字
height: 30, //按钮高度
width: 100, //按钮宽度
fileTypeExts: "*.jpg;*.png;*.jpeg;*.gif;*.bmp", //允许的文件类型
fileTypeDesc: "请选择", //文件说明
fileObjName:"img_path1",
onUploadSuccess: function (file, data, response) { //上传成功后的响应事件处理
$("#img_path1").attr("src","__PUBLIC__/upload/"+data);
$("#edit-img_path").val(data); //将上传后的图片复制给表单
}
});
});
<img src="__PUBLIC__/images/product.jpg" id="img_path1" width="200" height="200" /> <!-- 此处随便放一张暂无图片的背景图 -->
<br /><br />
<input type="file" name="img_path1" id="file_upload1" multiple="true">
控制器:ImageController.class.php
数据库字段:img_id,img_name,img_path(图片ID,图片名称,图片路径)
/*
*图片上传
*/
public function addProducts1(){
$Img = M('img');
$condition['img_name'] = md5_file($_FILES['img_path1']['tmp_name']); //图片名称md5加密
$upload = new \Think\Upload();// 实例化上传类
$upload->maxSize = 314572800;// 设置附件上传大小
$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
$upload->rootPath = './Public/upload/'; // 设置附件上传删除目录
$upload->savePath = ''; // 设置附件上传目录
$upload->replace = true;//覆盖相同文件
$upload->hash = true;
$upload->saveName = 'time';
$upload->autoSub = true;
$upload->subName = array('date','Ymd');
$img_info= $upload->uploadOne($_FILES['img_path1']); // 上传文件
if(!$img_info){// 上传错误提示错误信息
$this->error($upload->getError());
}else{
$data['img_name'] = $img_info['md5'];
$data['img_path'] = $img_info['savepath'].$img_info['savename'];
$result = $Img->add($data); //添加图片到数据库
if($result){
die($img_info['savepath'].$img_info['savename']);
}else{
$this->error("图片上传失败,请重新上传!");
}
}
}
注意:控制器图片上传的方法里面不要有session返回值,否则看不见缩略图!