SpringBoot(3) 文件上传和访问

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 }

前端简易代码

 1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <title>uploadimg.html</title>
 5     <meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
 6     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 7     <script src="/js/test.js" type="text/javascript"></script>
 8   </head>
 9 
10   <body>
11       <form enctype="multipart/form-data" method="post" action="/upload">
12         文件:<input type="file" name="head_img"/>
13         姓名:<input type="text" name="name"/>
14         <input type="submit" value="上传"/>
15        </form>
16    
17   </body>
18 </html>

文件大小配置,启动类里面配置

 1     @Bean
 2     public MultipartConfigElement multipartConfigElement() {
 3         MultipartConfigFactory factory = new MultipartConfigFactory();
 4         //单个文件最大
 5         factory.setMaxFileSize("10240KB"); //KB, MB
 6         //设置总上传的数据大小
 7         factory.setMaxRequestSize("1024000KB"); 
 8         return factory.createMultipartConfig();
 9         
10     }

在application.properties中添加上传路径,可用于在文件上传后的直接访问

web.upload-path=D:/.../src/main/resources/static/images/
spring.resources.static-locations=...:${web.upload-path} 

 

posted @ 2018-10-12 16:06  platycoden  阅读(3912)  评论(0编辑  收藏  举报