springboot+thymleaf处理单文件上传

1先写一个处理上传的工具类:html

public class FileUtil {

public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();
}
}

2写一个Form表单

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head >

</head>
<body >
<form enctype="multipart/form-data" method="post" th:action="@{/upload}">
图片
<input type="file" id="file1" placeholder="请上传商品图片" class="form-control" name="product_picture"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
3写一个跳转到上传页面的Controller 
 
@RequestMapping(value="/save")
public String updateproduct(){
return "upload";
}

4写上传
 
@RequestMapping(value="/upload", method = RequestMethod.POST)
public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,
                 HttpServletRequest request) {

   String contentType = file.getContentType();
   String fileName = file.getOriginalFilename();
   System.out.println("fileName-->" + fileName);
  System.out.println("getContentType-->" + contentType);
  String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
  System.out.println("filePath -->" + filePath );
   try {
     FileUtil.uploadFile(file.getBytes(), filePath, fileName);
  } catch (Exception e) {
// TODO: handle exception
   }
   return "uploadimg success";
}
 
5在浏览器输入 :http://localhost:8080/save 测试

6展现

相关文章
相关标签/搜索