当前位置:
首页 >
SpringBoot整合springDataJpa实现图片上传和显示
发布时间:2025/5/22
64
豆豆
生活随笔
收集整理的这篇文章主要介绍了
SpringBoot整合springDataJpa实现图片上传和显示
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
目录
- 使用工具
- 使用说明
- 使用maven的pom.xml文件
- 环境搭建
- 代码示例
- SQL代码
- java目录
- Img.java
- MyWebMvcConfigurerAdapter.java
- FileController.java
- ImgDao.java
- imgServiceImpl.java
- ImgService.java
- App.java
- resources目录
- index.html
- application.yml
- test目录
- AppTest.java
- 效果展示
使用工具
IDEA2018.2 MySQL5.6 JDK1.8
使用说明
需要在数据库中创建一个数据库,无需创建数据库表
SpringDtataJpa自动生成数据表
使用maven的pom.xml文件
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.gitee.vvcat</groupId><artifactId>picture_upload</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><name>picture_upload</name><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.7.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><project.version>0.0.1-SNAPSHOT</project.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.version></properties><dependencies><!--spring data jpa 依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><!--单元测试--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- database --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- 该模块需要启动web服务,需要该依赖--><!-- springBoot 的启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 引入thymeleaf的依赖包. --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build> </project>环境搭建
代码示例
SQL代码
CREATE DATABASE vvcat; USE vvcat; CREATE TABLE `img` (`id` int(11) NOT NULL AUTO_INCREMENT,`url` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;java目录
Img.java
package com.gitee.vvcat.bean;import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id;/*** @Author ꧁ʚVVcatɞ꧂* @Date 2019/11/12 11:34* @Version 1.0**/ @Entity(name = "img") public class Img {@Id@GeneratedValueprivate Integer id;private String url;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;} }MyWebMvcConfigurerAdapter.java
package com.gitee.vvcat.config;import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/*** @Author ꧁ʚVVcatɞ꧂* @Date 2019/11/12 11:32* @Version 1.0**/ @Configuration public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry){//指向外部目录registry.addResourceHandler("img//**").addResourceLocations("file:E:/img/");super.addResourceHandlers(registry);} }FileController.java
package com.gitee.vvcat.controller;import com.gitee.vvcat.bean.Img; import com.gitee.vvcat.service.ImgService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException;/*** @Author ꧁ʚVVcatɞ꧂* @Date 2019/11/12 11:32* @Version 1.0**/ @Controller public class FileController {@Autowiredprivate ImgService imgService;@Value("${com.vvcat}")//获取主机端口private String post;//获取本机ipprivate String host;//图片存放根路径private String rootPath = "E:";//图片存放根目录下的子目录private String sonPath = "/img/";//获取图片链接private String imgPath;private static final Logger logger = LoggerFactory.getLogger(FileController.class);@GetMapping("/")public String index(Model model,HttpServletRequest httpServletRequest){String imgPath = (String) httpServletRequest.getSession().getAttribute("imgPath");System.out.println("index:" + imgPath);model.addAttribute("imgPath",imgPath);return "index";}@RequestMapping(value = "upload")@ResponseBodypublic String upload(@RequestParam("test") MultipartFile file, HttpServletRequest httpServletRequest) {//返回上传的文件是否为空,即没有选择任何文件,或者所选文件没有内容。//防止上传空文件导致奔溃if (file.isEmpty()) {return "文件为空";}//获取本机IPtry {host = InetAddress.getLocalHost().getHostAddress();} catch (UnknownHostException e) {logger.error("get server host Exception e:", e);}// 获取文件名String fileName = file.getOriginalFilename();//logger.info("上传的文件名为:" + fileName);// 设置文件上传后的路径String filePath = rootPath + sonPath;logger.info("上传的文件路径" + filePath);logger.info("整个图片路径:" + host + ":" + post + sonPath + fileName);//创建文件路径File dest = new File(filePath + fileName);String imgPath = ("http://" + host + ":" + post + sonPath + fileName).toString();// 解决中文问题,liunx下中文路径,图片显示问题// fileName = UUID.randomUUID() + suffixName;// 检测是否存在目录if (!dest.getParentFile().exists()) {//假如文件不存在即重新创建新的文件已防止异常发生dest.getParentFile().mkdirs();}try {//transferTo(dest)方法将上传文件写到服务器上指定的文件file.transferTo(dest);//将链接保存到URL中Img imgTest = imgService.add(new Img(), imgPath);HttpSession session = httpServletRequest.getSession();//import javax.servlet.http.HttpSession;session.setAttribute("imgPath",imgPath);return "上传成功";} catch (Exception e) {return "上传失败";}} }ImgDao.java
package com.gitee.vvcat.repository;import com.gitee.vvcat.bean.Img; import org.springframework.data.jpa.repository.JpaRepository;/*** @Author ꧁ʚVVcatɞ꧂* @Date 2019/11/12 11:35* @Version 1.0**/ public interface ImgDao extends JpaRepository<Img,Integer> { }imgServiceImpl.java
package com.gitee.vvcat.service.impl;import com.gitee.vvcat.bean.Img; import com.gitee.vvcat.repository.ImgDao; import com.gitee.vvcat.service.ImgService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;/*** @Author ꧁ʚVVcatɞ꧂* @Date 2019/11/12 11:37* @Version 1.0**/ @Service public class imgServiceImpl implements ImgService {@Autowiredprivate ImgDao imgDao;@Overridepublic Img add(Img img, String path) {img.setUrl(path);return imgDao.save(img);} }ImgService.java
package com.gitee.vvcat.service;import com.gitee.vvcat.bean.Img;/*** @Author ꧁ʚVVcatɞ꧂* @Date 2019/11/12 11:36* @Version 1.0**/ public interface ImgService {/*** 添加图片地址* @param* @return*/Img add(Img img, String path); }App.java
package com.gitee.vvcat;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;/*** Hello world!**/ @SpringBootApplication public class App {public static void main( String[] args ){SpringApplication.run(App.class, args);} }resources目录
index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" > <head><title>上传图片</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <div th:if="${imgPath != null}"><img th:src="${imgPath}"> </div> <form action="/upload" method="POST" enctype="multipart/form-data">文件:<input type="file" name="test"/><input type="submit" value="上传"/> </form></body> </html>application.yml
server:port: 8080spring:http:encoding:force: truecharset: UTF-8thymeleaf:cache: falsecheck-template-location: truecontent-type: text/html; charset=utf-8enabled: trueencoding: UTF-8prefix: classpath:/templates/suffix: .htmlmode: LEGACYHTML5datasource:url: jdbc:mysql://localhost:3306/vvcat?characterEncoding=utf-8&serverTimezone=GMT%2B8username: rootpassword: 123456jpa:hibernate:ddl-auto: updateshow-sql: truecom:vvcat: ${server.port}test目录
AppTest.java
package com.gitee.vvcat;import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertTrue;import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest;/*** Unit test for simple App.*/ @SpringBootTest public class AppTest {/*** Rigorous Test :-)*/@Testpublic void shouldAnswerWithTrue(){System.out.println("hello world");} }效果展示
6.在网页显示图片 再次 访问 localhost:8080端口 可显示图片
总结
以上是生活随笔为你收集整理的SpringBoot整合springDataJpa实现图片上传和显示的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: SpringBoot和SpringSec
- 下一篇: JSP Cookie案例