layui 图片上传+表单提交+ Spring MVC

Layui 的上传是最常用的, 不可或缺, 记录一下代码, 以后复制都能用!!

1.前端HTML:
<div class="layui-form-item">

<label class="layui-form-label">修改头像</label>
<div class="layui-input-inline uploadHeadImage">
    <div class="layui-upload-drag" id="headImg">
        <i class="layui-icon"></i>
        <p>点击上传图片,或将图片拖拽到此处</p>
    </div>
</div>
<div class="layui-input-inline">
    <div class="layui-upload-list">
        <img class="layui-upload-img headImage" src="http://t.cn/RCzsdCq" id="demo1">
        <p id="demoText"></p>
    </div>
</div>

</div>

2.前端js:
<script type="text/javascript">

layui.use(["jquery", "upload", "form", "layer", "element"], function () {
    var $ = layui.$,
        element = layui.element,
        layer = layui.layer,
        upload = layui.upload,
        form = layui.form;
    //拖拽上传
    var uploadInst = upload.render({
        elem: ‘#headImg‘
        , url: ‘/upload/headImg‘
        , size: 500
        , before: function (obj) {
            //预读本地文件示例,不支持ie8
            obj.preview(function (index, file, result) {
                $(‘#demo1‘).attr(‘src‘, result); //图片链接(base64)
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                return layer.msg(‘上传失败‘);
            }
            //上传成功
            //打印后台传回的地址: 把地址放入一个隐藏的input中, 和表单一起提交到后台, 此处略..
            /*   console.log(res.data.src);*/
            window.parent.uploadHeadImage(res.data.src);
            var demoText = $(‘#demoText‘);
            demoText.html(‘<span style="color: #8f8f8f;">上传成功!!!</span>‘);
        }
        , 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();
            });
        }
    });
    element.init();
});

</script>

3.页面展示:

4.后台SpringMVC 接受:
/**

  • 个人信息上传
  • @return {Result}

*/
@RequestMapping(value = "/upload/headImg", method = {RequestMethod.POST})
@ResponseBody
public Object headImg(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {

if (SecurityUtils.getSubject().isAuthenticated() == false) {
    return "redirect:/backEnd/login";
}
String prefix="";
String dateStr="";
//保存上传
 OutputStream out = null;
InputStream fileInput=null;
try{
    if(file!=null){
        String originalName = file.getOriginalFilename();
        prefix=originalName.substring(originalName.lastIndexOf(".")+1);
         dateStr = format.format(new Date());
        String filepath = request.getServletContext().getRealPath("/static") + uploadDir + dateStr + "." + prefix;
        filepath = filepath.replace("\\", "/");
        File files=new File(filepath);
        //打印查看上传路径
        System.out.println(filepath);
        if(!files.getParentFile().exists()){
            files.getParentFile().mkdirs();
        }
        file.transferTo(files);
    }
}catch (Exception e){
}finally{
    try {
        if(out!=null){
            out.close();
        }
        if(fileInput!=null){
            fileInput.close();
        }
    } catch (IOException e) {
    }
}
Map<String,Object> map2=new HashMap<>();
Map<String,Object> map=new HashMap<>();
map.put("code",0);
map.put("msg","");
map.put("data",map2);
map2.put("src","../../../static"+uploadDir + dateStr + "." + prefix);
return map;

}

5.关于表单请求, 正常使用layui的表单上传就可以了.. 这里就不写了, 太简单了, 我其它博客有写,请去翻阅,嗯 ,就这样.......

相关推荐