软件编程
位置:首页>> 软件编程>> java编程>> Spring boot的上传图片功能实例详解

Spring boot的上传图片功能实例详解

作者:瓦力冫  发布时间:2022-10-09 09:52:00 

标签:Spring,boot,上传图片

简介

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

特点

1. 创建独立的Spring应用程序
2. 嵌入的Tomcat,无需部署WAR文件
3. 简化Maven配置
4. 自动配置Spring
5. 提供生产就绪型功能,如指标,健康检查和外部配置
6. 绝对没有代码生成和对XML没有要求配置

下面一段代码给大家介绍Spring boot 上传图片功能,具体代码如下所示:


@ResponseBody
 @RequestMapping(path = "/save_photo", method={RequestMethod.POST})
 public void addDish(@RequestParam("photos") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception
 {
   String path = null;// 文件路径
   String json = "";
   if (file!=null) {// 判断上传的文件是否为空
     String type = null;// 文件类型
     String fileName = file.getOriginalFilename();// 文件原名称
     System.out.println("上传的文件原名称:"+fileName);
     // 判断文件类型
     type = fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
     if (type!=null) {// 判断文件类型是否为空
       if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
         // 项目在容器中实际发布运行的根路径
         String realPath = request.getSession().getServletContext().getRealPath("/");
         // 自定义的文件名称
         String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
         // 设置存放图片文件的路径
         path = realPath+/*System.getProperty("file.separator")+*/trueFileName;
         System.out.println("存放图片文件的路径:"+path);
         // 转存文件到指定的路径
         file.transferTo(new File(path));
         System.out.println("文件成功上传到指定目录下");        
         }
         json = "{\"res\":1}";
       }else {
         System.out.println("不是我们想要的文件类型,请按要求重新上传");
         //return null;
         json = "{\"res\":0}";
       }
     }else {
       System.out.println("文件类型为空");
       //return null;
       json = "{\"res\":0}";
     }
   }else {
     System.out.println("没有找到相对应的文件");
     json = "{\"res\":0}";
     //return null;
   }
   response.setContentType("application/json;charset=UTF-8");
   response.getWriter().print(json);
 }

首先注意的是参数要加


@RequestParam("photos") MultipartFile file

你的html可能就类似这样的


<form action="/save_photo" enctype="multipart/form-data" method="post">
<input type="file" name="photos" /> <br>
<input type="submit" value="上传" />
</form>

总结

以上所述是小编给大家介绍的Spring boot的上传图片功能实例详解网站的支持!

来源:http://www.waitingfy.com/archives/1983

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com