coding喵
2019-03-06 13:07:38
springboot 上传图片并回显
之前也有做过上传图片的功能,不过是用在ssm的项目中,也有很多的不完美。
这次用的springboot,基本上对上传图片又有了一定的认识,想再这里记录一下。
/** * 上传图片 * * @return */ @RequestMapping(value = "/uploadImages", method = RequestMethod.POST) @ResponseBody public Result uploadImages(@RequestParam(value = "file") MultipartFile file) { if (file.isEmpty()) return Result.error("文件不存在"); String fileName = file.getOriginalFilename(); // 文件名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名 String filePath = "D://temp//"; // 上传后的路径,即本地磁盘 fileName = UUID.randomUUID() + suffixName; // 新文件名 File dest = new File(filePath + fileName); if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); } catch (IOException e) { e.printStackTrace(); } String filename = "/temp/" + fileName;//本地目录和生成的文件名拼接,这一段存入数据库 HashMap imgMap = new HashMap(); imgMap.put("imgUrl",filename); return Result.success(imgMap); }
设置资源映射路径:
/** * 资源映射路径 */ @Configuration public class MyWebAppConfigurer implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //外部访问路径映射到本地磁盘路径 registry.addResourceHandler("/temp/**").addResourceLocations("file:D:/temp/"); } }
由于springboot有默认上传文件大小,故在上传一些大size的图片,上传会失败,通过更改其默认设置:
spring.servlet.multipart.max-file-size=100MB spring.servlet.multipart.max-request-size=1000MB
不过springboot版本不同会导致上述语句有些偏差。
到这里上传图片已经完成,现在要关心就是回显了
目前我能做到回显就是外部访问图片了,即开启项目,使用外部路径访问:
localhost:8080/项目名/temp/图片名.jpg
所以我们需要拼接前面的字符串:
package com.********;//包名已注释 import com.********.TImg;//包名已注释 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; @Component public class ImgUtils { @Autowired Environment environment; public String getPort(){ return environment.getProperty("local.server.port"); } public String getHostIp(){ InetAddress localHost = null; try { localHost = InetAddress.getLocalHost(); } catch (UnknownHostException e) { } String ip = localHost.getHostAddress(); // 返回格式为:xxx.xxx.xxx return ip; } /** * 获取真实路径 * @param list */ public void getRealUrl(List<TImg> list,TImg img){ if(list != null) { for (TImg item : list) { if (!StringUtils.isEmpty(item.getImgUrl())) { item.setRealUrl("http://" + getHostIp() + ":" + getPort() + "/" + "项目名" + item.getImgUrl()); } } } if(img != null){ if(!StringUtils.isEmpty(img.getImgUrl())){ img.setRealUrl("http://" + getHostIp() + ":" + getPort() + "/" + "项目名" + img.getImgUrl()); } } } }
通过这个工具类去获取本项目所在ip和端口号,并将其与上传图片存储路径进行拼接。
在做这个功能时也有查阅借鉴他人博客。
期待指正与补充!
补充:springboot打成war包在tomcat上部署,那么定义在springboot配置文件中的端口号会失效,并改为使用tomcat中定义的端口号,所以动态获取ip和端口号面对外置tomcar会失效。
评论