layui+springmvc实现文件异步上传

一.单文件上传

前端代码

 <div class="layui-upload">
        <div class="layui-upload-list">
            <img class="layui-upload-img" id="demo1">
            <p id="demoText">p>
        div>
        <button type="button" class="layui-btn" id="upload_btn">上传图片button>

 div>
layui.use('upload', function() {
    var $ = layui.jquery
        , upload = layui.upload;

    //普通图片上传
    var uploadInst = upload.render({
        elem: '#upload_btn'
        , url: '/uploadImg'
        , 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('文件上传成功!');
            }
            if (res.code === 2) {
                return layer.msg('不支持该上传类型');
            }
            if (res.code === 3) {
                return layer.msg('文件为空');
            }else{
                return layer.msg('文件上传异常');

            }
            //上传成功
        }
        , error: function () {
            //演示失败状态,并实现重传
            var demoText = $('#demoText');
            demoText.html('上传失败 重试');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });
});

 

后端代码

在这边遇到一些问题:

1.springmvc的xml需要配置文件上传的类,否则会接收不了上传的文件

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        
        <property name="maxUploadSize" value="1000000000" />
    bean>

2.接收文件需要用@RequestParam("file")指定参数名称,layui默认文件上传的name是file

3.获取项目的绝对路径并拼接成新的图片地址

@Controller
public class FileUploadController {
    @RequestMapping("/uploadImg")
    @ResponseBody
    public RetResult upload(@RequestParam("file") MultipartFile multipartFile, HttpSession session){

        if (!StringUtils.isEmpty(multipartFile) && multipartFile.getSize()>0){
            String filename = multipartFile.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);
            if (filename.endsWith("jpg")||filename.endsWith("png")){

                String realPath = session.getServletContext().getRealPath("/")+"/image/"+new Date().getTime()+"."+suffix;
                File newfile = new File(realPath);
                try {
                    multipartFile.transferTo(newfile);
                    return RetResult.successRet(null);
                } catch (IOException e) {
                    e.printStackTrace();
                    return RetResult.errorRet(1,"文件上传异常");
                }
            }else {
                return RetResult.errorRet(2,"不支持该上传类型");
            }
        }else {
            return RetResult.errorRet(3,"文件为空");
        }

    }
}

  

转载于:https://www.cnblogs.com/wangxiayun/p/9265248.html

你可能感兴趣的:(java,javascript,后端)