Spring boot的上传图片功能实例详解
简介
SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,SpringBoot致力于在蓬勃发展的快速应用开发领域(rapidapplicationdevelopment)成为领导者。
特点
1.创建独立的Spring应用程序
2.嵌入的Tomcat,无需部署WAR文件
3.简化Maven配置
4.自动配置Spring
5.提供生产就绪型功能,如指标,健康检查和外部配置
6.绝对没有代码生成和对XML没有要求配置
下面一段代码给大家介绍Springboot上传图片功能,具体代码如下所示:
@ResponseBody
@RequestMapping(path="/save_photo",method={RequestMethod.POST})
publicvoidaddDish(@RequestParam("photos")MultipartFilefile,HttpServletRequestrequest,HttpServletResponseresponse)throwsException
{
Stringpath=null;//文件路径
Stringjson="";
if(file!=null){//判断上传的文件是否为空
Stringtype=null;//文件类型
StringfileName=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())){
//项目在容器中实际发布运行的根路径
StringrealPath=request.getSession().getServletContext().getRealPath("/");
//自定义的文件名称
StringtrueFileName=String.valueOf(System.currentTimeMillis())+"."+type;
//设置存放图片文件的路径
path=realPath+/*System.getProperty("file.separator")+*/trueFileName;
System.out.println("存放图片文件的路径:"+path);
//转存文件到指定的路径
file.transferTo(newFile(path));
System.out.println("文件成功上传到指定目录下");
}
json="{\"res\":1}";
}else{
System.out.println("不是我们想要的文件类型,请按要求重新上传");
//returnnull;
json="{\"res\":0}";
}
}else{
System.out.println("文件类型为空");
//returnnull;
json="{\"res\":0}";
}
}else{
System.out.println("没有找到相对应的文件");
json="{\"res\":0}";
//returnnull;
}
response.setContentType("application/json;charset=UTF-8");
response.getWriter().print(json);
}
首先注意的是参数要加
@RequestParam("photos")MultipartFilefile
你的html可能就类似这样的
总结
以上所述是小编给大家介绍的Springboot的上传图片功能实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!