當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot整合springDataJpa实现图片上传和显示
生活随笔
收集整理的這篇文章主要介紹了
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
- 下一篇: Windows10安装配置ChromeD