本文共 3375 字,大约阅读时间需要 11 分钟。
1.1 Trong file pom.xml thêm các phụ thuộc cần thiết
commons-io: commons-io: 2.5
commons-fileupload: commons-fileupload: 1.3.2
1.2 Trong file spring-mvc.xml thêm solverresolver:
2.1quivosrpc simplest
Langkah 1: Trong controller backend@RequestMapping("/upload")public Object upload(HttpSession session, @RequestParam("uploadFile") MultipartFile file) { boolean bool = false; ServletContext context = session.getServletContext(); String realPath = context.getRealPath("/upload"); String fileName = UUID.randomUUID().toString().replace("-", "").substring(0, 15) + "_file_" + file.getOriginalFilename(); try { file.transferTo(new File(realPath + "/" + fileName)); bool = true; } catch (IOException e) { e.printStackTrace(); } return bool ? "success" : "fail";}
2.2 Frontend code
$.ajax({ url: "/upload", type: "POST", data: new FormData($("#saveUploadForm")[0]), processData: false, contentType: false, success: function(result) { layer.msg(result); }, error: function(e) { layer.msg(e); }});
3.1 Backend code
private String uploadFile(String webPath, MultipartFile file, HttpSession session) { ServletContext context = session.getServletContext(); String realPath = context.getRealPath(webPath); String fileName = UUID.randomUUID().toString().replace("-", "").substring(0, 15) + "_file_" + file.getOriginalFilename(); try { File file1 = new File(realPath); if (!file1.exists()) { file1.mkdirs(); } file.transferTo(new File(realPath + "/" + fileName)); return webPath + "/" + fileName; } catch (IOException e) { e.printStackTrace(); return null; }}
3.2 Backend controller
@RequestMapping("/upload")public Object upload(@RequestParam("file") MultipartFile[] file, HttpSession session) { for (int i = 0; i < file.length; i++) { MultipartFile multipartFile = file[i]; String uploadFilePath = uploadFile("/upload", multipartFile, session); System.out.println(uploadFilePath); } return "success";}
3.3 Frontendcode
$.ajax({ url: "/upload", type: "POST", data: new FormData($("#saveFileForm")[0]), processData: false, contentType: false, success: function(result) { layer.msg(result); }, error: function(e) { layer.msg(e); }});
转载地址:http://annzk.baihongyu.com/