<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传文件夹</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script> </head> <body> <form action="/file/upload" enctype="multipart/form-data" method="post"> <input type='file' webkitdirectory > <button id="upload-btn" type="button">upload</button> </form> </body> <th:block th:include="include :: footer" /> <script> $(function () { var files = []; // 操作dom获取input的数据,多个input的话,用id获取 $(document).ready(function(){ $("input").change(function(){ files = this.files; }); }); // 绑定点击事件,ajax请求 $("#upload-btn").click(function () { var formData = new FormData(); for (var i = 0; i < files.length; i++) { // "file"是后台接口的参数名 formData.append("file", files[i]); } $.ajax({ url : "/system/test/wenjianjia", type : 'POST', data : formData, contentType : false, processData : false, cache : false, success : function(data) { console.log("成功!"); } }); }) }) </script> </html>
后台:
@RequestMapping(value = "/wenjianjia", headers = "content-type=multipart/*", method = RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile[] file) { for (MultipartFile mf : file) { File file1; String name = ""; try { //转换成这个对象,然后我们需要通过里面的FileItem来获得相对路径 CommonsMultipartFile f2 = (CommonsMultipartFile) mf; name = f2.getFileItem().getName(); String uploadPath = configService.selectConfigByKey("sys.inspect.uploadPath"); file1 = new File(uploadPath + "/test/" + name); file1.mkdirs(); file1.createNewFile(); //springmvc封装的方法,用于图片上传时,把内存中图片写入磁盘 mf.transferTo(file1); } catch (Exception e) { e.printStackTrace(); return "上传文件夹失败," + e.getMessage(); } } return "上传文件夹成功"; }
启动类配置:
@Bean(name = "multipartResolver") public MultipartResolver multipartResolver(){ CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setDefaultEncoding("UTF-8"); resolver.setResolveLazily(true); //resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常 resolver.setMaxInMemorySize(20971520);// 根据需求更换大小 resolver.setMaxUploadSize(104857600);// 根据需求更换大小 return resolver; }
application.yml
multipart.enabled: true