Springboot+layui上传文件携带参数前后台代码

Springboot+layui上传文件携带参数前后台代码

Scroll Down

1、首先官网:图片/文件上传

可以参考官网的例子。

注意:请求上传接口的额外参数。如:data: {id: 'xxx'} 从 layui 2.2.6 开始,支持动态值

2、前台代码

【1】html
<form class="layui-form">
    <div class="layui-form-item">
        <label class="layui-form-label"><span style="color: red">*</span >名称</label>
        <div class="layui-input-block">
            <input type="text" name="name" id="name" lay-verify="required" autocomplete="off" placeholder="请输入名称" class="layui-input">
        </div>
    </div>
 	    <div class="layui-form-item">
        <label class="layui-form-label"><span style="color: red">*</span>文件:</label>
        <button type="button" class="layui-btn layui-btn-normal" id="test8">选择文件		</button>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="test9">提交</button>
        </div>
    </div>
</form>
【2】Js
upload.render({
        elem: '#test8'
        ,url: '/upimg'
        ,auto: false
        ,exts: 'png|jpg'
        ,acceptMime:"image/*"//规定打开文件选择框时,筛选出的文件类型
        ,bindAction: '#test9'
        ,before: function(obj){
            layer.load(1, {
                content: '添加中...',
                success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '39px',
                        'width': '60px'
                    });
                }
            });
            this.data={"name":$("#name").val()};
        }
        ,done: function(res){
            layer.closeAll();
            if(res.code==0){
                layer.msg('添加成功', {
                    time: 1000,
                    icon: 1,
                    offset: '50px'
                }, function () {
                    location.reload()
                });
            }
        },error: function () {
            layer.closeAll('loading'); //关闭loading
            layer.msg('上传失败');
        }
    });
【3】Springboot
@PostMapping("/upimg")
    @ResponseBody
    public JSONObject userupimg(@RequestParam(value = "file")MultipartFile file, HttpServletRequest request) throws IOException {
        String name = request.getParameter("name");
        System.out.println(name);
        JSONObject res = new JSONObject();
        JSONObject resUrl = new JSONObject();
        String filename = UUID.randomUUID().toString().replaceAll("-", "");
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String filenames = filename + "." + ext;
        String pathname = "D:\\imgs\\" + filenames;
        file.transferTo(new File(pathname));
        resUrl.put("src", filenames);
        res.put("msg", "");
        res.put("code", 0);
        res.put("data", resUrl);
        return res;
    }