SpringMVC + MultipartFile实现文件上传

jar包别漏掉:

commons-fileupload

maven依赖:

<dependency>
   <groupId>commons-fileuploadgroupId>
   <artifactId>commons-fileuploadartifactId>
   <version>1.2.2version>
dependency>

Spring配置(这里采用的是注解配置):

@Bean
public MultipartResolver multipartResolver() throws IOException {
    CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver();
    commonsMultipartResolver.setUploadTempDir(new FileSystemResource("fileUpload/temp"));//上传中临时文件存放目录
    commonsMultipartResolver.setMaxUploadSize(2097152);//上传文件的总大小限制,这里设置为2G
    commonsMultipartResolver.setDefaultEncoding("UTF-8");//编码
    //commonsMultipartResolver.setResolveLazily();//延迟解析,解析文件的时候再抛异常
    //commonsMultipartResolver.setServletContext();
    commonsMultipartResolver.setMaxInMemorySize(1024);//缓存大小限制
    //commonsMultipartResolver.setMaxUploadSizePerFile();//单个文件大小限制
    //commonsMultipartResolver.setPreserveFilename();
    return commonsMultipartResolver;
}

HTML代码:

<div>
    <form  id="uploadTest" name="uploadTest"
           enctype="multipart/form-data" >
        <input type="file" name="file">
        <button class="btn" type="button" id="uploadButton">上传button>
    form>
div>

js代码:

$(function() {
    $("#uploadButton")
        .click(
            function() {
                $("#uploadTest")
                    .ajaxSubmit(
                        {
                            type : 'post',
                            url : "/test/uplodeTest",
                            contentType : "application/x-www-form-urlencoded; charset=utf-8",
                            success: function(data) {
                               console.log(data)
                            },
                            error: function (data)
                            {
                                console.log(data)
                            }
                        });
            });
});

后台使用Spring MVC:

/**
 * 文件上传测试
 *
 * @param file
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/uplodeTest")
public String uplodeTest(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {

    //这里的参数file名称要和中的name一致


    //配置主没有注入MultipartResolver这个Bean时,file会为null
    if (file == null) {
        return this.json(Constants.CODE_FAIL);
    }

    //文件不为空,写入上传路径
    if (!file.isEmpty()) {

        //上传的文件存入/fileUpload/目录下
        String realPath = request.getSession().getServletContext().getRealPath("/fileUpload/");
        //上传文件名
        String filename = file.getOriginalFilename();
        File filepath = new File(realPath, filename);
        //判断路径是否存在,如果不存在就创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        //将上传文件保存到一个目标文件当中
        file.transferTo(new File(realPath + File.separator + filename));
        return this.jsonOK();
    } else {
        return this.json(Constants.CODE_FAIL);
    }

}

你可能感兴趣的:(文件上传)