项目结构:
1、单文件上传
upload.html
upload file
http://localhost:8080/uploadfile/upload
package com.archibladwitwicke.springboot2.chapter03.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import java.io.File;@Controller@RequestMapping("/uploadfile")public class UploadFileController { @RequestMapping("/upload") public String upload() { return "/upload.html"; } @PostMapping("/upload") @ResponseBody public String upload(MultipartFile file) { if (file.isEmpty()) { return "file is null"; } String originFileName = file.getOriginalFilename(); String destFileLocation = "C:\\Users\\Administrator\\Desktop\\" + originFileName; File destFile = new File(destFileLocation); try { file.transferTo(destFile); return "upload ok! upload file location: " + destFileLocation; } catch (Exception ex) { return "upload false! reason: " + ex.getMessage(); } } @RequestMapping("/uploads") public String uploads() { return "/multiupload.html"; }}
2、多文件上传
multiupload.html
upload file
http://localhost:8080/uploadfile/uploads
package com.archibladwitwicke.springboot2.chapter03.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import java.io.File;@Controller@RequestMapping("/uploadfile")public class UploadFileController { @RequestMapping("/uploads") public String uploads() { return "/multiupload.html"; } @PostMapping("/uploads") @ResponseBody public String uploads(MultipartFile[] files) { String result = null; if (files.length == 0) { return "file is null"; } for (MultipartFile file : files) { String originFileName = file.getOriginalFilename(); String destFileLocation = "C:\\Users\\Administrator\\Desktop\\" + originFileName; File destFile = new File(destFileLocation); try { file.transferTo(destFile); result += "upload ok! upload file location: " + destFileLocation; } catch (Exception ex) { result = "upload false! reason: " + ex.getMessage(); } } return result; }}