layer提交图片与form表单同时提交数据

来源:互联网 发布:淘宝客吧 编辑:程序博客网 时间:2024/06/08 06:34

前端页面

    <button type="button" name="url" class="layui-btn" id="test1">上传图片</button>    <img class="layui-upload-img" id="photo" width="50" height="50">//点击上传图片选择图片后在这里展示    <p id="demoText"></p>//提交图片出错后,重新提交绑定在这里

layui图片上传方法
http://www.layui.com/doc/modules/upload.html 方法参考全部参数介绍

layui.use('upload', function(){          var $ = layui.jquery          ,upload = layui.upload;          //普通图片上传          var uploadInst = upload.render({             elem: '#test1'     /*根据绑定id,打开本地图片*/            ,url: '${ctx}/origin/user/saveOrUpdate'  /*上传后台接受接口*/            ,auto: false        /*true为选中图片直接提交,false为不提交根据bindAction属性上的id提交*/            ,bindAction: '#formSubmit'   /*提交图片*/            ,choose:function(obj){                //预读本地文件示例,不支持ie8                obj.preview(function(index, file, result){                  $('#photo').attr('src', result); //图片链接(base64)                });              }            ,done: function(res){              //如果上传失败              if(res.code > 0){                return layer.msg('上传失败');              }              //上传成功            }            ,error: function(){              //演示失败状态,并实现重传              var demoText = $('#demoText');              demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');              demoText.find('.demo-reload').on('click', function(){                uploadInst.upload();              });            }          });    }); 

form表单中的数据提交(因为图片提交在form表单中存在所以from表单的ajax提交(data : $(‘#businessForm’).serialize(),序列化 )方法会失败),需要通过formData 方法进行数据组装,另一种方法为formData.append(“username”, “Groucho”);

/*数据新增方法*/    function save() {        var fd = new FormData();        var formData = new FormData($( "#signupForm" )[0]);        $.ajax({            cache : true,            type : "post",            url : "${ctx}/origin/user/saveOrUpdate",            /* data : $('#signupForm').serialize(), */ // 你的formid            data : formData,  // 你的formid            async : false,            contentType: false,   //jax 中 contentType 设置为 false 是为了避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件            processData: false,   //当设置为true的时候,jquery ajax 提交的时候不会序列化 data,而是直接使用data            error : function(request) {                parent.layer.alert("网络超时");            },            success : function(data) {                if (data.code == 0) {                    parent.layer.msg("操作成功");                    parent.reLoad();                    var index = parent.layer.getFrameIndex(window.name);                    parent.layer.close(index);                } else {                    parent.layer.alert(data.msg)                }            }        });    }

后台接受(前段图片上传、form表单数据提交会访问两次此接口,有一次访问中form表单数据为空/user中的数据为空 。注意判断)

//@RequestParam(required=false)MultipartFile file 表示图片接受可为空@ResponseBody@RequestMapping (value="/saveOrUpdate")public Msg saveOrUpdate (@RequestParam(required=false)MultipartFile file, User user,HttpServletRequest request){        try {        //获取项目绝对路径,从例如:(D:\eclipse\workspaceproduct3\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\origin-web\static\abc)            String path = request.getSession().getServletContext().getRealPath("static/abc");            String pathPhoto = "/static/abc";            if(!file.isEmpty()){            String name = file.getOriginalFilename();//获取接受到的图片名称            File fi = new File(path,name);       //将path路径与图片名称联系在一起                if(!fi.getParentFile().exists()){    //判断是否存在path路径下的文件夹                fi.getParentFile().mkdirs();       //不存在创建path路径下的文件夹            }            file.transferTo(fi);                        //上传图片            user.setPhoto(pathPhoto+"/"+name);   //为保存图片路径        }         if(!StringUtil.isEmpty(user.getLoginname()) && !StringUtil.isEmpty(user.getPassword())){            userService.saveOrUpdate(user);         }    } catch (Exception e) {        e.printStackTrace();        return Msg.error();    }    return Msg.ok();}
    request.getSession().getServletContext() 获取的是Servlet容器对象,相当于tomcat容器了.    getRealPath("/") 获取实际路径,“/”指代项目根目录,所以代码返回的是项目在容器中的实际发布运行的根路径。    如:D:\apachetomcat6.0.32\webapps\cloudOABaseV4\hwtt_upload>