基于SpringBoot如何实现图片上传与显示
                                            小编给大家分享一下基于SpringBoot如何实现图片上传与显示,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
我们提供的服务有:成都网站设计、成都网站制作、微信公众号开发、网站优化、网站认证、娄底ssl等。为上千多家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的娄底网站制作公司
SpringBoot实现图片上传与显示:
效果图预览

思路
- 一般情况下都是将用户上传的图片放到服务器的某个文件夹中,然后将图片在服务器中的路径存入数据库。本Demo也是这样做的。 
- 由于用户自己保存的图片文件名可能跟其他用户同名造成冲突,因此本Demo选择了使用UUID来生成随机的文件名解决冲突。 
- 但是本Demo不涉及任何有关数据库的操作,便于演示,就用原来的文件名。 
步骤
pom相关依赖
- 基于Spring boot当然是继承了spring boot这不用多说 
- 具体依赖,主要是FreeMarker相关依赖为了展现页面,习惯用JSP也可以添加JSP的依赖,只是为了展示页面,这个不重要。 
org.springframework.boot spring-boot-starter-freemarker org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test 
application.properties相关配置
除了视图模板相关的配置,重点是要配置一下文件上传的内存大小和文件上传路径
server.port=8102 ### FreeMarker 配置 spring.freemarker.allow-request-override=false #Enable template caching.启用模板缓存。 spring.freemarker.cache=false spring.freemarker.check-template-location=true spring.freemarker.charset=UTF-8 spring.freemarker.content-type=text/html spring.freemarker.expose-request-attributes=false spring.freemarker.expose-session-attributes=false spring.freemarker.expose-spring-macro-helpers=false #设置面板后缀 spring.freemarker.suffix=.ftl # 设置单个文件最大内存 multipart.maxFileSize=50Mb # 设置所有文件最大内存 multipart.maxRequestSize=50Mb # 自定义文件上传路径 web.upload-path=E:/Develop/Files/Photos/
生成文件名
不准备生成文件名的可以略过此步骤
package com.wu.demo.fileupload.demo.util;
public class FileNameUtils {
 /**
  * 获取文件后缀
  * @param fileName
  * @return
  */
 public static String getSuffix(String fileName){
  return fileName.substring(fileName.lastIndexOf("."));
 }
 /**
  * 生成新的文件名
  * @param fileOriginName 源文件名
  * @return
  */
 public static String getFileName(String fileOriginName){
  return UUIDUtils.getUUID() + FileNameUtils.getSuffix(fileOriginName);
 }
}import java.util.UUID;
/**
 * 生成文件名
 */
public class UUIDUtils {
 public static String getUUID(){
  return UUID.randomUUID().toString().replace("-", "");
 }
}文件上传工具类
package com.wu.demo.fileupload.demo.util;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
 * 文件上传工具包
 */
public class FileUtils {
 /**
  *
  * @param file 文件
  * @param path 文件存放路径
  * @param fileName 源文件名
  * @return
  */
 public static boolean upload(MultipartFile file, String path, String fileName){
  // 生成新的文件名
  //String realPath = path + "/" + FileNameUtils.getFileName(fileName);
  //使用原文件名
  String realPath = path + "/" + fileName;
  File dest = new File(realPath);
  //判断文件父目录是否存在
  if(!dest.getParentFile().exists()){
   dest.getParentFile().mkdir();
  }
  try {
   //保存文件
   file.transferTo(dest);
   return true;
  } catch (IllegalStateException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return false;
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return false;
  }
 }
}Controller
package com.wu.demo.fileupload.demo.controller;
import com.wu.demo.fileupload.demo.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
@Controller
public class TestController {
 private final ResourceLoader resourceLoader;
 @Autowired
 public TestController(ResourceLoader resourceLoader) {
  this.resourceLoader = resourceLoader;
 }
 @Value("${web.upload-path}")
 private String path;
 /**
  * 跳转到文件上传页面
  * @return
  */
 @RequestMapping("test")
 public String toUpload(){
  return "test";
 }
 /**
  *
  * @param file 要上传的文件
  * @return
  */
 @RequestMapping("fileUpload")
 public String upload(@RequestParam("fileName") MultipartFile file, Map map){
  // 要上传的目标文件存放路径
  String localPath = "E:/Develop/Files/Photos";
  // 上传成功或者失败的提示
  String msg = "";
  if (FileUtils.upload(file, localPath, file.getOriginalFilename())){
   // 上传成功,给出页面提示
   msg = "上传成功!";
  }else {
   msg = "上传失败!";
  }
  // 显示图片
  map.put("msg", msg);
  map.put("fileName", file.getOriginalFilename());
  return "forward:/test";
 }
 /**
  * 显示单张图片
  * @return
  */
 @RequestMapping("show")
 public ResponseEntity showPhotos(String fileName){
  try {
   // 由于是读取本机的文件,file是一定要加上的, path是在application配置文件中的路径
   return ResponseEntity.ok(resourceLoader.getResource("file:" + path + fileName));
  } catch (Exception e) {
   return ResponseEntity.notFound().build();
  }
 }
} 页面
页面主要是from表单和下面的  ,其余都是细节。
<#--判断是否上传文件--> <#if msg??> ${msg}图片上传Demo 图片上传Demo
<#else > ${msg!("文件未上传")}
#if> <#--显示图片,一定要在img中的src发请求给controller,否则直接跳转是乱码--> <#if fileName??>

 建站
建站
 咨询
咨询 售后
售后
 建站咨询
建站咨询