easyui 行编辑中上传附件

前段时间写的一个系统需要实现在行编辑中上传附件的功能,最开始使用< input type=”file” />,但是提交表单的时候无法获取标签中的内容。后来使用先上传附件的方法实现这个功能。

使用技术:springMVC easyui ajax

思路大致如下:在行编辑中写一个链接,如“上传”、“附件”等等,点击链接弹出上传附件的页面,上传附件后后台处理,把路径传回jsp并接收,更新路径到行编辑中。后台读取有改变的行的数据,更新到数据库。

1、编写可编辑行表格

 <table id="mydatagrid" style="width:800px">
           </table>         
                  <script>
            $('#mydatagrid').datagrid({
                toolbar:'#tb',
                nowrap: false,
                striped: true,
                collapsible:true,
                url:'<%=request.getContextPath()%>/apps/appTest.do?method=json&id=${appTest.id}',
                remoteSort: false,
                singleSelect:true,
                idField:'id',
                columns:[[

                {title:'文本1',field:'text1', width:120,align:'center',
                    editor : {type :"validatebox",options : {  required: true}}},               
                {title:'文本2(提示内容)',field:'text2', width:140,align:'center',
                    editor : {type :"validatebox",options : {  required: true,missingMessage:'这里写提示内容'}}},
                {title:'数字',field:'number1', width:80,align:'center',
                    editor : {type :"numberbox",options : {  required: true ,
                    min:0,
                    validType:'number',
                    missingMessage:'请输入数字'}}},          
                {title:'路径',field:'filePath',hidden:true, width:100,align:'center',
                    editor : {type :"validatebox",options : {  }}},   
                {title:'附件',field:'file',width:180,align:'center',
                    formatter:function (value, row, index) {
                        if(row.resultFile != "" && row.resultFile != null) {
                            var arr = row.resultFile.split('\\');
                            var resultFileName = arr[arr.length-1];
                            var download = "<a href='<%=request.getContextPath()%>/apps/appTest.do?method=download&filepath="+row.filePath+"'>"+下载+"</a>";                      
                            var upload = "<a href='#' onclick='addFile("+index+");'>上传</a>";
                            return download+"<br>"+upload;
                        }else{                      
                            var str = "<a href='#' onclick='addFile("+index+");'>上传</a>";
                            return str;
                        }
                    }
                }
                ]],
                pagination:false,
                onDblClickRow: onRowClick 
            });

    function onRowClick(rowIndex, row){
        $('#mydatagrid').datagrid('beginEdit', rowIndex);
    }           

    function addNew(){
        $('#mydatagrid').datagrid('endEdit', lastIndex);       
        $('#mydatagrid').datagrid('appendRow');        
        var lastIndex = $('#mydatagrid').datagrid('getRows').length-1;
        $('#mydatagrid').datagrid('selectRow', lastIndex);
        $('#mydatagrid').datagrid('beginEdit', lastIndex);

    }
    function endEdit(){
        var rows = jQuery("#mydatagrid").datagrid('getRows');  
        for ( var i = 0; i < rows.length; i++) {  
            jQuery("#mydatagrid").datagrid('endEdit', i);
        }       
    }
    function deleteSelections(){
        endEdit();

        var rows = jQuery('#mydatagrid').datagrid("getSelections"); 
        if(rows == null || rows.length <=0){
            jQuery.messager.alert("info","请选中一行!", "info");
            return;
        }

        var copyRows = [];
        for ( var j= 0; j < rows.length; j++) {
            copyRows.push(rows[j]);
        }
        for(var i =0;i<copyRows.length;i++){    
            var index = jQuery('#mydatagrid').datagrid('getRowIndex',copyRows[i]);
            jQuery('#mydatagrid').datagrid('deleteRow',index); 
        }

    }
function addFile() {
        //打开上传附件页面时需要先将行编辑结束编辑,否则更新路径回行编辑页面时会把其他内容清空
        endEdit();  
        var link = '<%=request.getContextPath()%>/apps/appTest.do?method=addFile;
        jQuery.layer({
            type: 2,
            shade: [0.5, '#000'],
            fix: false,
            title: '上传附件',
            iframe: {src : link},
            area: ['340px' , '180px']
        }); 
    }
</script>

2、上传附件upload.jsp

<%@ page contentType="text/html;charset=UTF-8" %>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script type="text/javascript" charset="utf-8">
    var contextPath="<%=request.getContextPath()%>";
    function saveData(){
        var params = jQuery("#iForm").serializeJson();  
        var isValid = $("#iForm").form('validate');
    //通过ajax异步提交表单,提交成功后后台返回data
        $.ajaxFileUpload({
            type:"POST",
            url:'<%=request.getContextPath()%>/apps/appTest.do?method=uploadFile',
            data:params,
            dataType:'json',
            fileElementId:['uploadFile'],
            error:function(data){
                alert('提交失败');
            },
            success:function(data){
                if(data != null && data.message != null){
                    parent.layer.alert(data.message, 1);
                } else {
                    parent.layer.alert('操作成功!', 1);
                }
                //接收返回的filePath
                var file = JSON.stringify(data.filePath);
                var filePath = file.replace(/\"/g,"");
                //使用updateRow将filePath更新回父页面,即行编辑的页面
                parent.$('#mydatagrid').datagrid('updateRow', { index:${index} , row: { filePath: filePath} });
                closeDiv();

            }
        });
    }
    function closeDiv(){
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);  
    }
</script>
</head>

<body style="margin:5px;">
<div class="easyui-layout" data-options="fit:true">  
  <div data-options="region:'center',border:false,cache:true">
  <form id="iForm" name="iForm" method="post">
  <input type="hidden" id="id" name="id" value=""/>

  <table class="easyui-form" style="width:300px;" align="center">    
        <tr>        
            <td align="left">
                <input name="uploadFile" type="file" id="uploadFile"/>
            </td>           
        </tr>
        <tr>
            <td colspan="4" align="center">
            <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-save'" onclick="javascript:saveData();" >保存</a> 
            <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'" onclick="javascript:closeDiv();" >关闭</a>
            </td>
        </tr>   
  </table>
  </form>
</div>
</div>
</body>
</html>

3、上传附件的jsp文件中使用ajax异步提交表单,上传成功后后台返回上传的路径到前端

    @RequestMapping(params = "method=uploadFile")
    @ResponseBody
    public byte[] uploadFile(@RequestParam("uploadFile") CommonsMultipartFile file)
            throws IOException {
        JSONObject jsonObject = new JSONObject();

        String path = "";
        try {// 上传文件
            //取得文件名         
            fileName = file.getOriginalFilename()+"_"+new Date().getTime();
            // 获得上传附件的服务器端路径.
            path = request.getSession().getServletContext().getRealPath("/upload");
            // 创建文件类型对象:
            File newFile=new File(path+"/"+fileName);
            //通过CommonsMultipartFile的方法直接写文件
            file.transferTo(newFile);
            //保存在数据库中的相对路径
            String filePath = "upload/"+fileName;
            jsonObject.put("filePath", filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject.toString().getBytes("UTF-8");

    }
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页