欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

项目笔记之jqGrid实现文件上传以及回显

程序员文章站 2022-05-18 18:36:03
...

业务需求:

使用jqGridt添加功能时实现文件的上传及表格刷新和文件的回显

实现实例图:
项目笔记之jqGrid实现文件上传以及回显
项目笔记之jqGrid实现文件上传以及回显
实现步骤:
前台代码:

<%--
  Created by IntelliJ IDEA.
  User: 15757
  Date: 2019/12/5
  Time: 11:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<div class="col-md-12 row" id="bt"  style="background-color:#F5F5F5;height:70px;margin-left: 0px;display:block">
    <font class="col-md-3 col-md-offset-5" style="margin-top: 20px;font-size: 25px;font-weight: bold">轮播图详情</font>

</div>
<script>
   $("#tt").jqGrid(
       {
           url:'${pageContext.request.contextPath}/lbt/findLbt',
           datatype : "json",
           styleUI:'Bootstrap',// 用于整合bootstrap的样式
           colNames:['名称','封面','描述','创建日期','状态'],
           colModel : [
               {name:'id'},
               {
                   name:'src',
                   align:'center',//居中
                   editable: true,//可编辑
                   formatter:showPicture,//添加事件回显文件
                   edittype:'file',//类型为文件
                   editoptions:{enctype:"multipart/form-data"}//设置文件的传输机制以二进制
                   },
               {
                   name:'title',
                   editrules:{required : true},
                   editable:true
               },
               {name:'addTime'},
               //editrules:{required : true} 非空验证
               {
                   name:'state',
                   editable:true,
                   editrules:{required : true},//非空验证
                   edittype:'select',//添加下拉框
                   editoptions:{value:"1:正常;2:禁用"}//添加下拉框值

               },
           ],
           multiselect:true,//指定复选框
           height:290,
           autowidth:true,//数据表格是否自适应父容器的大小宽度
           page:1, // 默认显示第几页
           rowNum : 3,
           rowList : [ 3, 6, 9,12],
           pager : '#pg',
           /*editrules:{
                  required : true,
                  custom:true,},*/
           //sortname : 'id',
           viewrecords : true,//总条数
           // sortorder : "desc",
           caption : "轮播图信息展示",
           editurl : "${pageContext.request.contextPath}/lbt/edit"
       }).navGrid("#pg", {edit : true,add : true,del : true},
               {
                 //控制修改操作
                   closeAfterEdit:true,
                   afterSubmit:function (result) {
                       if(result=="error"){
                           return "111"
                       }
                       console.log(result),
                           $.ajaxFileUpload({
                               url:'${pageContext.request.contextPath}/lbt/upload',
                               fileElementId:'src',
                               data:{id:result.responseJSON.data},
                               type:'post',
                               datatype:'json',
                               success:function () {
                                   $("#tt").trigger("reloadGrid")
                               }
                           });
                       return "123";
                   }



               },{
                    //控制添加操作
                   closeAfterAdd:true,
                    //required:true,
           afterSubmit:function (result) {
               console.log(result),
               $.ajaxFileUpload({
                   url:'${pageContext.request.contextPath}/lbt/upload',
                   fileElementId:'src',
                   data:{id:result.responseJSON.data},
                   type:'post',
                   datatype:'json',
                   success:function () {
                       $("#tt").trigger("reloadGrid")
                   }
               });
               return "123";
           }

               },{
           closeAfterDel:true,

   });
   function showPicture(cellvalue){
       return "<img src='${pageContext.request.contextPath}/img/"+cellvalue+ "' height='80' width='100'/>";
   }
   
   function importLbt() {
       $.ajax({
          url:'${pageContext.request.contextPath}/lbt/importLbt',
           type:'post',
           success:function () {
           }
           
       });
       
   }
   function openModal() {
       console.log(1111)
       $("#lbt-modal").modal("show")

   }
   function save11() {
       var form=new FormData(document.getElementById("fm"));
       console.log(form);
       $.ajax({
           url:'${pageContext.request.contextPath}/lbt/importExcel',
           data:form,
           type:'post',
           datatype:'josn',
           contentType: false,
           processData: false,
           success:function (data) {
               $("#lbt-modal").modal("hide");
               $("#tt").trigger("reloadGrid")
           }


       });
   }

</script>


<div class="modal fade"  role="dialog" id="lbt-modal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">导入表格文件</h4>
            </div>
            <div class="modal-body">
              <form enctype="multipart/form-data" id="fm">
                  <input type="file" value="选择导入文件" name="xls">
              </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="save11()">保存</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<ul class="nav nav-tabs">
    <%--<li role="presentation" class="active"><a href="#">Home</a></li>--%>
    <li role="presentation"><a href="${pageContext.request.contextPath}/lbt/exportLbt">导出轮播图数据</a></li>
    <%--<li role="presentation" onclick="importLbt()"><a href="">导入轮播图数据</a></li>--%>
    <li role="presentation"><a onclick="openModal()">导入轮播图数据</a></li>

</ul>

<table id="tt"></table>
<div id="pg" style="height: 50px"></div>







重点代码:

{
                   name:'src',
                   align:'center',//居中
                   editable: true,//可编辑
                   formatter:showPicture,//添加事件
                   edittype:'file',//类型为文件
                   editoptions:{enctype:"multipart/form-data"}//设置文件的传输机制以二进制
                   },



//事件函数 回显图片
function showPicture(cellvalue){//cellvalue是单元格内的值
       return "<img src='${pageContext.request.contextPath}/img/"+cellvalue+ "' height='80' width='100'/>";
   }

文件上传重要代码:


{
                  {
                 //控制修改操作
                   closeAfterEdit:true,
                   afterSubmit:function (result) {
                       if(result=="error"){
                           return "111"
                       }
                       console.log(result),
                           $.ajaxFileUpload({
                               url:'${pageContext.request.contextPath}/lbt/upload',
                               fileElementId:'src',//设置传输文件的名字,相当于from中的name
                               data:{id:result.responseJSON.data},//往后台传的参数
                               type:'post',
                               datatype:'json',
                               success:function () {
                                   $("#tt").trigger("reloadGrid")//成功后刷新表格
                               }
                           });
                       return "123";
                   }



               },

后台代码:

@RequestMapping("upload")
    public void upload(String id, MultipartFile src, HttpServletRequest request) throws IOException {
        if(src==null){
            System.out.println(1234);
        }
        System.out.println(src.getOriginalFilename());
        //文件上传
        //获取此项目根目录的绝对路径,即是真实路径。
        String realPath = request.getSession().getServletContext().getRealPath("/");
        //在此绝对路径下面创建img文件夹
        File file = new File(realPath + "img");
        //如果这个文件夹不存在
        if (!file.exists()) {
            //创建一个
            file.mkdir();
        }
        String filename = src.getOriginalFilename();
        src.transferTo(new File(file.getPath(),filename));
        //System.out.println(filename);
        Lbt lbt=new Lbt();
        lbt.setId(id).setSrc(filename);
        lbtService.modify(lbt);
    }

当执行修改时需要判断文件是否为空 ,为空返回error就不上传文件

if(oper.equals("edit")){
            if(lbt.getSrc().equals("")){
                Lbt lbt1 = lbtService.findOne(new Lbt().setId(lbt.getId()));
                lbt.setSrc(lbt1.getSrc());
                map.put("data","error");
                lbtService.modify(lbt);
                return map;
            }
            Lbt lbt1 = lbtService.findOne(new Lbt().setId(lbt.getId()));
            lbt.setSrc(lbt1.getSrc());
            lbtService.modify(lbt);
            map.put("code",200);
            map.put("data",lbt.getId());
        }
相关标签: 项目笔记