springboot 文件和表单一起提交multipart/form

最近用form实现文件上传采用enctype="multipart/form-data方式,后端用springboot

遇到的问题如下:

1.不需要配置什么额外解析器multipartResolver,CommonsMultipartResolver 不需要配置!(网上有文章说配置的都是用的springmvc ,或者比较老),这玩意 springboot已经内置

2.什么request转换不需要 !ShiroHttpServletRequest,如何转换成MultipartHttpServletRequest 不需要!

前端:

  1. <form:form id="inputForm" modelAttribute="fileTemplet" action="${ctx}/file/save" method="post" class="form-horizontal" enctype="multipart/form-data
  2. <input id="fileTitle" name="fileTitle" value="" htmlEscape="false" maxlength="255" class="form-control required" />
  3. <input id="file" name="file" type="file" maxlength="255" class="form-control required" />

后端:

  1. controller:
  2. @RequestMapping(value = "save")
  3. public String save(HttpServletRequest request, FileTemplet fileTemplet, Model model, RedirectAttributes redirectAttributes ,@RequestParam(name = "file") MultipartFile file)
  4. //input参数可以通过下面2种方式获取
  5. request.getParameter("fileTitle");
  6. fileTemplet.getFileTitle();
  7. //上传文件
  8. String filePath = FileUtils.uploadSingleFile(templetTypePath, file);

下载文件实现:

  1. public static String uploadSingleFile(String pathname, MultipartFile fileList) {
  2. try{
  3. String filename = fileList.getOriginalFilename();
  4. File dir = new File(pathname);
  5. if (!dir.exists()) {
  6. dir.mkdirs();
  7. }
  8. String filepath = pathname + filename;
  9. File serverFile = new File(filepath);
  10. fileList.transferTo(serverFile);
  11. return filepath;
  12. }catch (Exception e) {
  13. e.printStackTrace();
  14. return "";
  15. }
  16. }

 

(0)

相关推荐