Spring MVC会自动解析multipart/form-data请求,将multipart中的对象封装到MultipartRequest对象中,所以在Controller中使用@RequestParam注解就可以映射multipart中的对象了,如:@RequestParam("file") MultipartFile file

    1. import org.javaweb.utils.FileUtils;
    2. import org.javaweb.utils.HttpServletResponseUtils;
    3. import org.springframework.stereotype.Controller;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.bind.annotation.RequestParam;
    6. import org.springframework.web.bind.annotation.ResponseBody;
    7. import org.springframework.web.multipart.MultipartFile;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import java.io.File;
    11. import java.io.IOException;
    12. import java.util.LinkedHashMap;
    13. import java.util.Map;
    14. import static org.javaweb.utils.HttpServletRequestUtils.getDocumentRoot;
    15. @Controller
    16. @RequestMapping("/FileUpload/")
    17. public class FileUploadController {
    18. @RequestMapping("/upload.php")
    19. public void uploadPage(HttpServletResponse response) {
    20. HttpServletResponseUtils.responseHTML(response, "<!DOCTYPE html>\n" +
    21. "<html lang=\"en\">\n" +
    22. "<head>\n" +
    23. " <meta charset=\"UTF-8\">\n" +
    24. " <title>File upload</title>\n" +
    25. "</head>\n" +
    26. "<body>\n" +
    27. "<form action=\"/FileUpload/upload.do\" enctype=\"multipart/form-data\" method=\"post\">\n" +
    28. " <p>\n" +
    29. " 用户名: <input name=\"username\" type=\"text\"/>\n" +
    30. " 文件: <input id=\"file\" name=\"file\" type=\"file\"/>\n" +
    31. " </p>\n" +
    32. " <input name=\"submit\" type=\"submit\" value=\"Submit\"/>\n" +
    33. "</form>\n" +
    34. "</body>\n" +
    35. "</html>");
    36. }
    37. @ResponseBody
    38. @RequestMapping("/upload.do")
    39. public Map<String, Object> upload(String username, @RequestParam("file") MultipartFile file, HttpServletRequest request) {
    40. // 文件名称
    41. String filePath = "uploads/" + username + "/" + file.getOriginalFilename();
    42. File uploadFile = new File(getDocumentRoot(request), filePath);
    43. // 上传目录
    44. File uploadDir = uploadFile.getParentFile();
    45. // 上传文件对象
    46. Map<String, Object> jsonMap = new LinkedHashMap<String, Object>();
    47. if (!uploadDir.exists()) {
    48. uploadDir.mkdirs();
    49. }
    50. try {
    51. FileUtils.copyInputStreamToFile(file.getInputStream(), uploadFile);
    52. jsonMap.put("url", filePath);
    53. jsonMap.put("msg", "上传成功!");
    54. } catch (IOException e) {
    55. jsonMap.put("msg", "上传失败,服务器异常!");
    56. }
    57. return jsonMap;
    58. }
    59. }

    访问示例中的文件上传地址:http://localhost:8000/FileUpload/upload.do,如下图:
    4. 3. Spring MVC文件上传 - 图1
    后门成功的写入到了网站目录:
    4. 3. Spring MVC文件上传 - 图2