springboot文件上传 MultipartFile file,源自SpringMVC
MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效)
1 @Controller 2 public class FileController { 3 4 private static final String filePath = "D:/.../src/main/resources/static/images/"; 5 6 7 @RequestMapping(value = "upload") 8 @ResponseBody 9 public JsonData upload(@RequestParam("head_img") MultipartFile file,HttpServletRequest request) { 10 11 //file.isEmpty(); 判断图片是否为空 12 //file.getSize(); 图片大小进行判断 13 String name = request.getParameter("name"); 14 System.out.println("用户名:"+name); 15 16 // 获取文件名 17 String fileName = file.getOriginalFilename(); 18 System.out.println("上传的文件名为:" + fileName); 19 20 // 获取文件的后缀名,比如图片的jpeg,png 21 String suffixName = fileName.substring(fileName.lastIndexOf(".")); 22 System.out.println("上传的后缀名为:" + suffixName); 23 24 // 文件上传后的路径 25 fileName = UUID.randomUUID() + suffixName; 26 System.out.println("转换后的名称:"+fileName); 27 28 File dest = new File(filePath + fileName); 29 30 try { 31 file.transferTo(dest); 32 33 return new JsonData(0, fileName); 34 } catch (IllegalStateException e) { 35 e.printStackTrace(); 36 } catch (IOException e) { 37 e.printStackTrace(); 38 } 39 return new JsonData(-1, "fail to save ", null); 40 } 41 42 }