自定义文件上传
一、前端
1、引入jquery.js,jquery.form.js,layer.js文件
2、html代码
<div class="goods-detail-wrap"> <form action="" class="goods-detail-form" onsubmit="return false;"> <p class="form-item"> <label>商品图片:</label> <ul class="goodsimg-list"> <volist id="image" name="sku['sku_images']"> <li><img src="{$image}" alt="" width="80" height="80"><br/><a href="javascript:;" onclick="delete_img(this)" data-key="{$key}" data-flag="true">删除</a></li> </volist> <li class="upload-li" id="upload-btn"> <label for="upload" class="upload-lable"> <span class="add-img">+</span> <span class="add">上传图片</span> </label> <!-- <input id="upload" class="upload-img" type="file"> --> </li> </ul> </p> </form> </div>
3、css代码
.goods-detail-wrap .goodsimg-list { display: inline-block; position:relative; left:140px; top:-40px; } .goods-detail-wrap .goodsimg-list li{ float:left; width:80px; height:80px; box-sizing: border-box; margin-right:10px; } .goods-detail-wrap .goodsimg-list img{ width:100%; height:100%; } .goods-detail-wrap .goodsimg-list .upload-img{ width:0; height:0; opacity: 0; } .goods-detail-wrap .goodsimg-list .upload-li{ border:1px dashed #e9e9e9; position:relative; } .goods-detail-wrap .goodsimg-list .upload-li:hover{ border:1px dashed #27a9e3; } .goods-detail-wrap .goodsimg-list .upload-lable{ width:100%; height:100%; text-align: center; position:absolute; z-index: 10; } .goods-detail-wrap .goodsimg-list .add { line-height:25px; color: #999; position:relative; top:-25px; } .goods-detail-wrap .goodsimg-list .add-img{ font-size:60px; color: #999; }
3、隐藏表单
<form id="upload-form" data-url="xx" method="post" enctype="multipart/form-data"> <input type="file" name="file" style="display:none;"/>
<input type="hidden" name="path" value="xx" />
</form>
4、js基类upload.js
$(function(){ var _formObj = $("#upload-form"); var _url = $("#upload-form").attr("data-url"); var _type = 'post'; var _container = $('.goodsimg-list'); $("#upload-btn").click(function (){ _formObj.find("input[type='file']").click(); }) _formObj.find("input[type='file']").change(function (){ var options = { type:_type, url:_url, beforeSubmit:showRequest, success:showResponse, error:showerror }; _formObj.ajaxSubmit(options); function showRequest(){ var file = _formObj.find("input[type='file']").val(); if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(file)) { layer.alert("图片类型必须是.gif,jpeg,jpg,png中的一种",{icon: 1,title:'提示',time:1000}); return false; } if(_container.find('li').size()>6){ layer.alert("只能上传6张图片",{icon: 1,title:'提示',time:1000}); return false; } } function showResponse(res){ _formObj.find("input[type='file']").val('');//清空 if(typeof(res) != "object"){ var res = $.parseJSON(res); } if(res.code == 1){//成功 layer.alert(res.msg,{icon: 1,title:'提示',time:1000}); _container.find('li:last').before('<li><img width="80" height="80" src="'+res.data.url+'" alt=""><br/><a href="javascript:;" onclick="delete_img(this)" data-key="'+res.data.key+'">删除</a></li>');; }else if(res.code == 3){//超时 layer.alert(res.msg,{icon: 2,title:'提示',time:1000}); setTimeout(function(){window.location.href=res.url;},1000); }else{//出错 layer.alert(res.msg,{icon: 2,title:'提示',time:1000}); } } function showerror(){ //todo... } }) }) function delete_img(obj){ if($(obj).attr("data-flag")=='false'){ return ''; } //防止重复点击 $(obj).attr("data-flag","false"); var url = 'xxx'; var id = {$Think.get.id}; var key = $(obj).attr('data-key'); var data = {key:key,id:id}; $.post(url,data,function (rs){ if(typeof(rs) != "object"){ var rs = $.parseJSON(rs); } if(rs.code == 1){ //layer.alert(rs.msg,{icon: 1,title:'提示',time:1000},function(){ // window.location.href=rs.url; //}); $(obj).parent().remove(); layer.alert(rs.msg,{icon: 1,title:'提示',time:1000}); }else if(rs.code == 3){ //layer.alert(rs.msg,{icon: 1,title:'提示',time:1000},function(){ // window.location.href=rs.url; //}); layer.alert(rs.msg,{icon: 2,title:'提示',time:1000}); setTimeout(function(){window.location.href=rs.url;},1000); }else{ layer.alert(rs.msg,{icon: 2,title:'提示',time:1000}); $(obj).attr("data-flag","true"); } return ; }); }
二、后端代码:
/** * 先把图片上传的本地(外网),再上传到资源服务器,删除本地,更新数据库 * 图片上传 */ public function uploadProductEditImage(){ $path = I('post.path','','strip_tags,htmlspecialchars'); $id = I('post.id',0,'strip_tags,htmlspecialchars'); $return = array(); if($_FILES && $id){ $fileData = $_FILES['file']; $file_path = './Data/Uploads/tmp/'; if(!is_dir($fileUrl)){ @mkdir($file_path,0777); } $fileUrl = $file_path.time()*mt_rand(1,1000)*mt_rand(1,1000)."jpg"; if(@move_uploaded_file($fileData['tmp_name'],$fileUrl)){ $return['name']=''; $return['url']=''; $return['key']=''; $resResource = $this->uploadResourceFile($fileUrl); //删除本地图片 @unlink($fileUrl); if(!empty($resResource)){ $return = $resResource; } $resUpdate = $this->updateProductEditImage($id,$return['url']); if(!$resUpdate){ echo $this->ajaxReturn(array('code'=>2,'msg'=>'数据出现异常')); } $return['key']= $resUpdate-1; echo $this->ajaxReturn(array('code'=>1,'msg'=>'上传图片成功','data'=>$return)); }else{ echo $this->ajaxReturn(array('code'=>2,'msg'=>'数据出现异常')); } }else{ echo $this->ajaxReturn(array('code'=>2,'msg'=>'操作有误')); } } /** * 请求远程资源服务器 * @param unknown $fileUrl * @return string[]|NULL[] */ public function uploadResourceFile($fileUrl){ $return = array(); if (class_exists('\CURLFile')) { $curlData['file'] = new \CURLFile(\realpath($fileUrl));//php 5.6 }else{ $curlData['file'] = '@'.$fileUrl; } $respone = $this->curlPost($curlData); if($respone){ $curlRes = json_decode($respone); if($curlRes->status == 1){ // 文件上传后的网络名称 $return['name'] = $curlRes->data->fileName; // 文件上传后的网络路径 $return['url'] = $this->url.$curlRes->data->fileName; }else{ echo $this->ajaxReturn(array('code'=>2,'msg'=>'数据出现异常')); } }else{ echo $this->ajaxReturn(array('code'=>2,'msg'=>'数据出现异常')); } return $return; } /** * 保存图片路径 */ public function updateProductEditImage($id,$value){ if($id){ //todo }else{ return false; } } /** * 删除图片 */ public function deleteProductEditImg(){ $key = I('post.key','','strip_tags,htmlspecialchars'); $id = I('post.id',0,'strip_tags,htmlspecialchars'); if(!$this->sessionId){ echo $this->ajaxReturn(array('code'=>3,'msg'=>'登陆已过期','url'=>'xxx')); } if($id){ $where['id'] = $id; $skus = $this->getSku($where); if($skus){ $sku = $skus[0]; $ser_sku_images = unserialize($sku['sku_images']); if(empty($ser_sku_images) || !isset($ser_sku_images[$key])){ echo $this->ajaxReturn(array('code'=>2,'msg'=>'操作有误')); } unset($ser_sku_images[$key]);//删除指定key $sku_images = array_values($ser_sku_images); //$sku_images = $ser_sku_images; $data['sku_images'] = serialize($sku_images); $data['update_time'] = NOW_TIME; $result = $this->updateSku($where,$data); if($result){ echo $this->ajaxReturn(array('code'=>1,'msg'=>'删除图片成功')); }else{ echo $this->ajaxReturn(array('code'=>2,'msg'=>'操作有误')); } } }else{ echo $this->ajaxReturn(array('code'=>2,'msg'=>'操作有误')); } }