栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

基于SpringBoot实现图片上传与显示

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于SpringBoot实现图片上传与显示

本文为大家分享了SpringBoot实现图片上传与显示的具体代码,供大家参考,具体内容如下

SpringBoot实现图片上传与显示:Demo地址

效果图预览

思路

  • 一般情况下都是将用户上传的图片放到服务器的某个文件夹中,然后将图片在服务器中的路径存入数据库。本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 {

 
 public static String getSuffix(String fileName){
  return fileName.substring(fileName.lastIndexOf("."));
 }

 
 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 {

 
 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;

 
 @RequestMapping("test")
 public String toUpload(){
  return "test";
 }

 
 @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";
 }

 
 @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表单和下面的 ,其余都是细节。



 
 图片上传Demo


图片上传Demo <#--判断是否上传文件--> <#if msg??> ${msg}
<#else > ${msg!("文件未上传")}
<#--显示图片,一定要在img中的src发请求给controller,否则直接跳转是乱码--> <#if fileName??> <#else>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/140156.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号