• Thinkphp 图片上传


    案例:广告的增删改查

    步骤:

    1引用 js

    2 填写 input type=" file" 的id  

    3 填写 url

    4后台保存地址

    5前台成功后的处理

    广告添加页

    <div class="modal-header no-padding">
    	<div class="table-header">
    		<i class="icon-lock"></i>
    		<button type="button" class="close" data-dismiss="modal">×</button>
    		添加广告
    	</div>
    </div>
    
    <div class="modal-body overflow-visible">
    	<label class="control-label pull-left" style="padding-right:20px;">类别</label>
    	<select id="class_id"   name="class_id" class="left">
    		<option value="">不限</option>
    		<volist name="advertise_class" id="vo">
    			<eq name="vo.id" value="$map.class_id">
    				<option value="{$vo.id}" selected >{$vo.name}</option>
    				<else />
    				<option value="{$vo.id}" >{$vo.name}</option>
    			</eq>
    		</volist>
    	</select>
    </div>
    
    <div class="modal-body overflow-visible">
    	<div class="control-group">
    		<label class="control-label" for="name">广告名称</label>
    		<div class="controls">
    			<input type="text" required="required" id="name" name="name" placeholder="广告名称"/>
    		</div>
    	</div>
    
    	<div class="control-group">
    		<label class="control-label" for="url">广告地址</label>
    		<div class="controls">
    			<input type="text" required="required" id="url" name="url"
    				   placeholder="注意添加http://"/>
    		</div>
    	</div>
    	<div class="control-group">
    		<label class="control-label" for="Pic"  >广告图片</label>
    		<div class="controls">
    			<input type="file"  name="Pic" id="Pic"  style="display: none"   onchange="uploadFile();" />
    			<label for="Pic">
    			<img  id="image"  class="image" width="15%" height="15%" style=" auto; height:80px;" src="__PUBLIC__/HomeStyle/images/photo.png"  >
    			</label>
    			<!--<input type="file"  id="image"  style="display: none"   onchange="uploadFile('{:U('Admin/Advertisement/image')}', 'imageCom','logo_success');" />-->
    			<!--<label for="image">-->
    			<!--<img  class="logo_success" width="13%" height="13%"  src="__PUBLIC__/HomeStyle/images/photo.png"  >-->
    			<!--</label>-->
    
    			<!--<input id="file0"  type="file" size="10" accept="image/*"  placeholder="点击上传"    onchange="uploadFile('{:U('Admin/Advertisement/image')}', 'file0','advertise_pic');" />-->
    			<!--  <!–用for属性绑定file控件–>   -->
    			<!--  <label for="file0">        -->
    			     <!--<img id="pic" class="advertise_pic"  width="13%" height="13%" src="__PUBLIC__/HomeStyle/images/photo.png" alt=" " />  -->
    			<!--  </label>   -->
    		</div>
    	</div>
    
    	<div class="control-group">
    		<label class="control-label" for="sort">排序</label>
    		<div class="controls">
    			<input type="text" required="required" id="sort" name="sort"
    				   placeholder="数字越大越靠前"/>
    		</div>
    	</div>
    
    	<div class="control-group">
    		<label class="control-label" for="note">备注</label>
    		<div class="controls" >
    			<textarea type="text" style="height: 50px" cols="20" rows="10"  required="required" id="note" name="note" />
    		</div>
    	</div>
    </div>
    
    <div class="modal-footer">
    	<button data-dismiss="modal" class="btn btn-small">
    		<i class="icon-remove"></i>
    		取消
    	</button>
    	<button type="button" class="btn btn-small btn-primary" onclick="$.doAdd('{:U('Admin/Advertisement/doAdd')}', this);">
    		<i class="icon-ok"></i>确认
    	</button>
    </div>
    <input id="pic_hidden" value="">
    <script src="__PUBLIC__/HomeStyle/js/ajaxfileupload.js"></script>
    <script type="text/javascript">
    	//图片上传
    	function uploadFile() {
    		$.ajaxFileUpload({
    			url: "{:U('Admin/Advertisement/upload')}",  //请求控制器地址
    			secureuri: false,   
    			fileElementId: 'Pic',  //input type=“file”标签的id
    			dataType: 'json',  //返回值类型
    			success: function (data)  //服务器成功响应处理函数
    			{
    				if (data.code ==1) {
    					$('#pic_hidden').val(data.msg);
    					data.msg = data.msg + '?' + parseInt(Math.random() * 1000); //添加随机数
    					$('.image').attr('src', data.msg);
    				} else {
    					alert(data.msg);
    				}
    			},
    		})
    	}
    
    
    
    
    		jQuery(function($){
    			$.extend({
    				doAdd : function(url, obj)
    				{
    					var obj = $(obj).parents('form');
    
    					$.ajax({
    						url : url,
    						type : 'get',
    						data : {
    								class_id:$('#class_id').val(),
    								name:$('#name').val(),
    								url:$('#url').val(),
    							    pic:$('#pic_hidden').val(),
    								sort:$('#sort').val(),
    								note:$('#note').val()
    						},
    						success : function(res)
    						{
    							$.lagou.alert(res.msg, res.code, 2);
    							$.lagou.formHide();
    							location.reload();
    						}
    					});
    				}
    			});
    		});
    
    
    
    
    </script>
    

      

    后台:

    <?php
    /**广告管理
     * Created by PhpStorm.
     * User: Administrator
     * Date: 2017/5/3
     * Time: 17:33
     */
    
    namespace AdminController;
    
    class AdvertisementController extends BaseController {
    
        protected $AdvertisementObj = null;
        protected $Advertise_class=null;
    
        public function __construct()
        {
            parent::__construct();
            $this->AdvertisementObj = M('Advertisement');
            $this->Advertise_class=M('Advertise_class');
        }
    
        /**
         *
         */
        public function index()
        {
            //获取页面中所有name标签的内容
            $map=I();
            //移除$map中所有可以转为false的值,如:false,0,‘0’,arrary(),null,'',
           // $a=array_filter($map);
             $a=$map;
            //名称
            if(!empty($a['name'])){
                $where['am.name']=array('LIKE','%'.$a['name'].'%');  //联表查询有两个name时,搜索条件要带表名。
            }
            //审核状态
            //empty 若变量已存在、非空字符串或者非零,则返回 false 值;反之返回 true。
            //换句话说,""、0、"0"、NULL、FALSE、array()、var $var; 以及没有任何属性的对象都将被认为是空的,如果 var 为空,则返回 TRUE。
            //if  0代表假  非0代表真
            if($a['state']!=""){
                $where['state']=array('EQ',$a['state']);
            }
            //类别
            if(!empty($a['class_id'])){
                $where['class_id']=array('EQ',$a['class_id']);
            }
            //var_dump($where);
            //分页
            $total=$this->AdvertisementObj->where($where)->count();//获取总页数
            $Page= new ThinkPages($total,10);//显示10个页码
            $Page->setConfig('first','首页');
            $Page->setConfig('prev','上一页');
            $Page->setConfig('next','下一页');
            $Page->setConfig('last','尾页');
            $showPage = $Page->show();
            //搜索结果
            // $data=$this-> companyModel->where($where)->page(I('get.p',1),20)->order('create_time desc')->join('as com left join lg_city_category as city on com.city=city.id left join lg_trade as tr on com.trade=tr.id left join lg_basic_config_category as bc on com.stage=bc.id')->field('com.id as id,com.name as name,com.trade,city.name as city,tr.name as trade,bc.name as stage,com.state as state')-> select();
            $data=$this->AdvertisementObj->where($where)->page(I('get.p',1),10)->order('sort desc')->join('as am left join lg_advertise_class as ac on am.class_id=ac.id')->field('am.id,am.name,am.create_time,am.sort,am.state,ac.name as class_name') ->select();//get.p 表示页码,如果不存在则赋值1,每页20行。
            //var_dump($data);
            $advertise_category=$this->Advertise_class->order('sort desc')->select();
            //上一次搜索条件
            $this->assign('map',$a);
            $this->assign('advertise_class',$advertise_category);
            //分页
            $this->assign('page',$showPage);
            //列表
            $this->assign('data', $data);
            $this->display();
    
        }
    
        /**
         * 添加
         */
        public function add()
        {
            $advertise_category=$this->Advertise_class->order('sort desc')->select();
            $this->assign('advertise_class',$advertise_category);
            $this->display();
        }
    
        /**
         * 执行添加
         */
        public function doAdd()
        {
            $data=I();
            $data['create_time'] = time();
            $data['state'] = 1;
            $rs = $this->AdvertisementObj->add($data);
            if($rs){
                $msg['code'] = 1;
                $msg['msg'] = '添加成功';
            }else{
                $msg['code'] = 0;
                $msg['msg'] = '添加失败';
            }
            $this->ajaxReturn($msg);
        }
    
    
        //图片处理
        public function upload()
        {
            $upload = new ThinkUpload();// 实例化上传类
            $upload->maxSize   =    3145728 ;// 设置附件上传大小
            $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->savePath  =     './Advertisement/Pic/'; // 设置图片上传目录,默认在 Uploads文件下。
            $upload->saveName =     time().'_'.mt_rand(); //生成随机名称,如果想实现替换可以定位用户id: (string)session('user.id');
            $upload->saveExt = 'jpeg';
            $upload->subName = ""; 
            $upload->replace = true;
            $upload->hash = false;
            $info = $upload->upload();
            if(!$info){
                $msg['code']=0;
                $msg['msg']=$upload->getError();
            }else{
                $msg['code']=1;
                $msg['msg']= '/Uploads/Advertisement/Pic/'.$info['Pic']['savename'];  //想前台返回地址和新名称
            }
            $this->ajaxReturn($msg);
        }
        /**
         * 修改
         */
        public function edit()
        {
            $id = I('get.id');
            $info = $this->AdvertisementObj->where('id='.$id)->find();
            $advertise_category=$this->Advertise_class->order('sort desc')->select();
            $this->assign('advertise_class',$advertise_category);
            $this->assign('info', $info);
            $this->display();
        }
    
        /**
         * 修改
         */
        public function doEdit()
        {
                $data = I();
                $rs = $this->AdvertisementObj->save($data);
                if($rs===false){
                    $msg['code'] = 0;
                    $msg['msg'] = '修改失败';
                }else{
                    $msg['code'] = 1;
                    $msg['msg'] = '修改成功';
                }
                $this->ajaxReturn($msg);
    
        }
    
        /*
         * 删除
         */
        public function delete()
        {
            $id = I('get.id');
            $rs=$this->AdvertisementObj->where('id='.$id)->delete();
            if ($rs==0||$rs===false) {
                $msg['code'] = 0;
                $msg['msg'] = '删除失败';
            } else {
                $msg['code'] = 1;
                $msg['msg'] = '删除成功';
            }
            $this->ajaxReturn($msg);
        }
    
        //审核通过
        public function adopt(){
    //        $this->ajaxReturn($_GET["id"]);
    //        return;
            $id = I('get.id');
            $data['state']=1;
            $res = $this->AdvertisementObj->where('id='.$id)->save($data);
            if($res===false){
                $msg['code'] = 0;
                $msg['msg'] = '操作失败';
            }else{
                $msg['code'] = 1;
                $msg['msg'] = '操作成功';
            }
            $this->ajaxReturn($msg);
        }
    
        //审核拒绝
        public function refuse(){
            $id = I('get.id');
            $data['state']=2;
            $res = $this->AdvertisementObj->where('id='.$id)->save($data);
            if($res===false){
                $msg['code'] = 0;
                $msg['msg'] = '操作失败';
            }else{
                $msg['code'] = 1;
                $msg['msg'] = '操作成功';
            }
            $this->ajaxReturn($msg);
        }
    
    
    
    }
    

      

    修改页

    <div class="modal-header no-padding">
    	<div class="table-header">
    		<i class="icon-lock"></i>
    		<button type="button" class="close" data-dismiss="modal">×</button>
    		添加广告
    	</div>
    </div>
    
    <div class="modal-body overflow-visible">
    	<label class="control-label pull-left" style="padding:0px 10px;">类别</label>
    	<select id="class_id"   name="class_id" class="left">
    		<option value="">不限</option>
    		<volist name="advertise_class" id="vo">
    			<eq name="vo.id" value="$info.class_id">
    				<option  value="{$vo.id}" selected >{$vo.name}</option>
    				<else />
    				<option value="{$vo.id}" >{$vo.name}</option>
    			</eq>
    		</volist>
    	</select>
    </div>
    
    <div class="modal-body overflow-visible">
    	<div class="control-group">
    		<label class="control-label" for="name">广告名称</label>
    		<div class="controls">
    			<input type="text" value="{$info.name}" required="required" id="name" name="name" placeholder="广告名称"/>
    		</div>
    	</div>
    
    	<div class="control-group">
    		<label class="control-label" for="url">广告地址</label>
    		<div class="controls">
    			<input type="text" required="required" id="url" name="url" value="{$info.url}"
    				   placeholder="注意添加http://"/>
    		</div>
    	</div>
    	<div class="control-group">
    		<label class="control-label" for="Pic" >广告图片</label>
    		<div class="controls">
    			<input type="file"  name="Pic" id="Pic"  style="display: none"   onchange="uploadFile();" />
    			<label for="Pic">
    				<if condition="$info.pic eq ''">
    					<img  class="image" width="15%" height="15%" style=" auto; height:80px;" src="__PUBLIC__/HomeStyle/images/photo.png"  >
    					<else/>
    						<img  id="image"  class="image" width="15%" height="15%" style=" auto; height:80px;" src="{$info.pic}"  >
    				</if>
    			</label>
    		</div>
    	</div>
    
    	<div class="control-group">
    		<label class="control-label" for="sort">排序</label>
    		<div class="controls">
    			<input type="text" required="required" id="sort" name="sort" value="{$info.sort}"
    				   placeholder="数字越大越靠前"/>
    		</div>
    	</div>
    
    	<div class="control-group">
    		<label class="control-label" for="note">备注</label>
    		<div class="controls" >
    			<textarea type="text" style="height: 50px" cols="20" rows="10"  required="required" id="note"  name="note" >{$info.note}</textarea>
    		</div>
    	</div>
    </div>
    
    <div class="modal-footer">
    	<button data-dismiss="modal" class="btn btn-small">
    		<i class="icon-remove"></i>
    		取消
    	</button>
    	<button type="button" class="btn btn-small btn-primary" onclick="doEdit();">
    		<i class="icon-ok"></i>确认
    	</button>
    </div>
    <input id="pic_hidden" value="">
    <script src="__PUBLIC__/HomeStyle/js/ajaxfileupload.js"></script>
    <script type="text/javascript">
    	//图片上传
    	function uploadFile() {
    		$.ajaxFileUpload({
    			url: "{:U('Admin/Advertisement/upload')}",
    			secureuri: false,
    			fileElementId: 'Pic',
    			dataType: 'json',
    			success: function (data)  //服务器成功响应处理函数
    			{
    				if (data.code ==1) {
    					$('#pic_hidden').val(data.msg);
    					data.msg = data.msg + '?' + parseInt(Math.random() * 1000);
    					$('.image').attr('src', data.msg);
    				} else {
    					alert(data.msg);
    				}
    			},
    		})
    	}
    
    			function  doEdit()
    			{
    				var adv_class_id = $("#class_id").find("option:selected").attr("value");
    				$.ajax({
    					url : "{:U('Admin/Advertisement/doEdit')}",
    					type : 'post',
    					data : {
    						id:{$info.id},
    						class_id:adv_class_id,
    						name:$('#name').val(),
    						url:$('#url').val(),
    						pic:$('#pic_hidden').val(),
    						sort:$('#sort').val(),
    						note:$('#note').val()
    					},
    					success : function(res)
    					{
    						//alert(res);
    						$.lagou.alert(res.msg, res.code, 2);
    						$.lagou.formHide();
    						location.reload();
    					}
    				});
    			}
    
    
    
    </script>
    

      

    列表页

    <extend name="Public/base" />
    
    
    {// 导航}
    <block name="breadcrumb">
    <li class="active">广告管理</li>
    </block>
    
    {// 左侧菜单}
    <block name="sidebar">
    	<include file="Public/sidebar" nav="advertise"/>
    </block>
    
    {// 主体}
    <block name="main">
    <div class="row-fluid">
    
    	<h3 class="header blue lighter smaller">
    		<form action="{:U('Admin/Advertisement/index')}" method="get">
    			<div class="dataTables_wrapper">
    				<div class="grid_conent" id="m_search_div">
    					<div class="grid" style="28%">
    						<label class="control-label pull-left">广告名称:</label>
    						<input name="name" value="{$map.name}" type="text" id="search_name" class="pull-left" />
    					</div>
    					<div class="grid" style=" 28%;"  >
    						<label class="control-label pull-left">审核状态:</label>
    						<select name="state" class="pull-left">
    							<option value="">不限</option>
    							<option value="0" <?php if($map['state']=='0'):?> selected="selected"<?php endif;?> >待审核</option>
    							<option value="1" <?php if($map['state']=='1'):?>selected="selected" <?php endif;?> >已通过</option>
    							<option value="2" <?php if($map['state']=='2'):?>selected="selected"<?php endif;?> >已拒绝</option>
    						</select>
    
    					</div>
    					<div class="grid" style="auto;">
    						<label class="control-label pull-left" style="padding-left:26px;">类别:</label>
    						<select name="class_id" class="left">
    							<option value="">不限</option>
    							<volist name="advertise_class" id="vo">
    								<eq name="vo.id" value="$map.class_id">
    									<option value="{$vo.id}" selected >{$vo.name}</option>
    									<else />
    									<option value="{$vo.id}" >{$vo.name}</option>
    								</eq>
    							</volist>
    						</select>
    					</div>
    					<div class="add_link" style="  auto; float: right;">
    						<button class="btn btn-primary btn-small" onclick="$.lagou.formShow('{:U('Admin/Advertisement/add')}');" type="button"><i class="icon-plus"></i>添加广告</button>
    					</div>
    					<div style="auto; float: right; padding-top:1px; "><button type="submit" class="btn btn-primary btn-small pull-left" id="search_submit"><i ></i>搜索</button></div>
    
    				</div>
    			</div>
    		</form>
    	</h3>
    	<div class="table-header">广告列表</div>
    	<div class="dataTables_wrapper" role="grid">
    	<table id="data_table" class="table table-striped table-bordered table-hover" style="margin-bottom:0px;">
    		<thead>
    			<tr>
    				<th>广告名称</th>
    				<th>创建时间</th>
    				<th>排序</th>
    				<th>类别</th>
    				<th>审核状态</th>
    				<th>审核</th>
    				<th>操作</th>
    			</tr>
    		</thead>
    		<tbody>
    			<?php foreach ($data as $key => $value): ?>
    				<tr>
    					<td>{$value.name}</td>
    					<td>{$value.create_time|date="Y-m-d H:i", ###}</td>
    					<td>{$value.sort}</td>
    					<td>{$value.class_name}</td>
    					<td><eq name="value.state" value="0"><i class="waitting">等待审核</i><else/><eq name="value.state" value="1">已通过<else/> <eq name="value.state" value="2"><i class="red">已拒绝</i><else/> </eq> </eq></eq></td>
    					<td>
    						<div class="hidden-phone visible-desktop action-buttons">
    							<a href="javascript:;" onclick="$.adopt('{:U('Admin/Advertisement/adopt', array('id'=>$value['id']))}');" class="green"  >
    								<i>通过</i>
    							</a>
    							<a href="javascript:;" onclick="$.refuse('{:U('Admin/Advertisement/refuse', array('id'=>$value['id']))}');" class="red" >
    								<i>拒绝</i>
    							</a>
    						</div>
    					</td>
    					<td>
    						<div class="hidden-phone visible-desktop action-buttons">
    							<a href="javascript:;" onclick="$.lagou.formShow('{:U('Admin/Advertisement/edit', array('id'=>$value['id']))}');" class="blue tooltip-info no-hover-underline" data-rel="tooltip" data-original-title="编辑资料">
    								<i class="icon-pencil bigger-130"></i>
    							</a>
    							<a href="javascript:;" onclick="$.del('{:U('Admin/Advertisement/delete', array('id'=>$value['id']))}');" class="red tooltip-error no-hover-underline" data-rel="tooltip" data-original-title="删除"><i class="icon-trash bigger-130"></i></a>
    						</div>
    					</td>
    				</tr>
    			<?php endforeach ?>
    		</tbody>
    	</table>
    		<!-- 分页 -->
    		<div class="row-fluid">
    			<div class="page">{$page}</div>
    		</div>
          </div>
    	</div>
    
    </block>
    
    {// js}
    <block name="js">
    
    
    	<script type="text/javascript">
    
    			jQuery(function($) {
    				// 这就是全选按钮
    				$('table th input:checkbox').on('click' , function(){
    					var that = this;
    					$(this).closest('table').find('tr > td:first-child input:checkbox')
    					.each(function(){
    						this.checked = that.checked;
    						$(this).closest('tr').toggleClass('selected');
    					});	
    				});
    				
    				$.extend({
    
    					action : function(url, obj)
    					{
    						var obj = $(obj).parents('form');
    
    						$.ajax({
    							url : url,
    							type : 'get',
    							data : obj.serialize(),
    							success : function(res)
    							{
    								$.lagou.alert(res.msg, res.code, 2);
    								$.lagou.formHide();
    								location.reload();
    							}
    						});
    					},
    
    					del : function(url)
    					{
    
    						$.lagou.confirm('确认删除吗?', function(res){
    							if (res) {
    								$.get(url, function(response){
    									//alert(response);
    									$.lagou.alert(response.msg, response.code, 2);
    									location.reload();
    								});
    							}
    						});
    					},
    					//通过
    					adopt : function(url)
    					{
    						$.lagou.confirm('确定要通过吗?', function(res){
    							if (res) {
    								$.get(url, function(response){
    									$.lagou.alert(response.msg, response.code, 2);
    									location.reload();
    								});
    							}
    						});
    					},
    					//拒绝
    					refuse : function(url)
    					{
    						$.lagou.confirm('确定拒绝吗?', function(res){
    							if (res) {
    								$.get(url, function(response){
    									$.lagou.alert(response.msg, response.code, 2);
    									location.reload();
    								});
    							}
    						});
    					}
    
    
    				});
    			})
    		</script>
    </block>
    

      

  • 相关阅读:
    【Intellij Idea】设置JDK
    MarkDown换行
    Git 查看/修改用户名、邮箱
    JavaScript对象
    Javascript事件
    第十次会议
    第九次会议
    详细设计文档
    第八次会议
    第七次会议
  • 原文地址:https://www.cnblogs.com/hao-1234-1234/p/7067411.html
Copyright © 2020-2023  润新知