這篇文章主要介紹“基于SpringBoot怎么實現圖片上傳及圖片回顯”,在日常操作中,相信很多人在基于SpringBoot怎么實現圖片上傳及圖片回顯問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”基于SpringBoot怎么實現圖片上傳及圖片回顯”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
CREATE DATABASE wdzldb` USE `wdzldb`; DROP TABLE IF EXISTS `book`; CREATE TABLE `book` ( `bookid` int(11) NOT NULL AUTO_INCREMENT, `bookName` varchar(120) DEFAULT NULL, `price` float DEFAULT NULL, `pubDate` date DEFAULT NULL, `author` varchar(20) DEFAULT NULL, `version` int(11) DEFAULT '0', `state` int(11) DEFAULT NULL, `pic` varchar(50) DEFAULT NULL, PRIMARY KEY (`bookid`) ) ENGINE=InnoDB AUTO_INCREMENT=157 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*Data for the table `book` */ insert into `book`(`bookid`,`bookName`,`price`,`pubDate`,`author`,`version`,`state`,`pic`) values (22,'Java實戰開發3',34,'2021-07-28','王磊',1,1,NULL), (53,'Java實戰開發666',120,'2021-07-24','諸葛亮',0,1,NULL), (61,'Java實戰開發1',39,'2021-07-29','王磊',0,1,NULL), (62,'Java實戰開發1',39,'2021-07-29','王磊',0,0,NULL), (66,'Java實戰開發1',39,'2021-07-29','王磊',0,0,NULL), (67,'SpringCloud微服務實戰',45,'2021-08-11','王帆',0,0,NULL), (68,'SPringBoot整合JDBC',56,'2021-08-11','周瑜',0,1,NULL), (70,'SpringBoot入門與提高',78,'2021-08-11','曹操',0,1,NULL), (71,'Java實戰開發5',100,'2021-07-23','諸葛亮',0,0,NULL), (72,'Java虛擬機深入',23,'2021-08-11','趙紫陽',0,1,NULL), (73,'深入學習Java虛擬機',69,'2021-08-05','黃蓋',0,0,NULL), (74,'JSP開發技術',34,'2021-08-12','王超',0,1,NULL)
先搭建基本框架,完成業務層、DAO 層、pojo 等模塊編寫,并調試通過 springdata 正常使用。
web 啟動器、thymeleaf 模板啟動器、springdata 啟動器及數據庫驅動等
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
application.yml 數據源的基本信息配置、jpa 是否顯示 sql 及 下劃線等
spring: datasource: username: root password: root url: jdbc:mysql://127.0.0.1:3306/wdzldb?allowMultiQueries=true&useUnicode=true&allowPublicKeyRetrieval=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver jpa: show-sql: true hibernate: naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
application.properties
下面多數是在使用阿里的初始化工具時,自動生成的
除了下面的上傳保存的路徑是自定義的
# 應用名稱 spring.application.name=springboot_other # 應用服務 WEB 訪問端口 server.port=8080 # THYMELEAF (ThymeleafAutoConfiguration) # 開啟模板緩存(默認值: true ) spring.thymeleaf.cache=false # 檢查模板是否存在,然后再呈現 spring.thymeleaf.check-template=true # 檢查模板位置是否正確(默認值 :true ) spring.thymeleaf.check-template-location=true #Content-Type 的值(默認值: text/html ) spring.thymeleaf.content-type=text/html # 開啟 MVC Thymeleaf 視圖解析(默認值: true ) spring.thymeleaf.enabled=true # 模板編碼 spring.thymeleaf.encoding=UTF-8 # 要被排除在解析之外的視圖名稱列表,?逗號分隔 spring.thymeleaf.excluded-view-names= # 要運?于模板之上的模板模式。另? StandardTemplate-ModeHandlers( 默認值: HTML5) spring.thymeleaf.mode=HTML # 在構建 URL 時添加到視圖名稱前的前綴(默認值: classpath:/templates/ ) spring.thymeleaf.prefix=classpath:/templates/ # 在構建 URL 時添加到視圖名稱后的后綴(默認值: .html ) spring.thymeleaf.suffix=.html #上傳的絕對路徑 file.upload.path=d://save/images/ #絕對路徑下的相對路徑 file.upload.relativePath=/images/ #文件上傳大小限制 spring.servlet.multipart.max-file-size=2048000
注意:日期和圖片處理
@Data
@Entity(name = "book") //要求必須有@Id 也
@ApiModel(value = "圖書實體", description = "圖書中明細屬性")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) //注意:默認的是序列,針對Oracle的
private Integer bookId;
@ApiModelProperty(value = "圖書名")
private String bookName;
@ApiModelProperty(value = "圖書作者")
private String author;
private Float price;
@Column(name = "pic")
private String picpath; // 封面
@DateTimeFormat(pattern = "YYYY-MM-dd")
private Date pubDate; //出版日期
}dao 接口直接使用 springdata 提供的統一接口 JpaRepository ,其中已經包含了基本的操作。也可以按約定規則自己定義其他方法
注意:繼承接口時需要指定泛型
public interface IBookDao extends JpaRepository<Book, Integer> {
List<Book> queryBooksByBookName(String bookName);
List<Book> findBooksByPriceBetween(Float min, Float max);
List<Book> findBooksByBookNameLike(String bookName);
List<Book> findAllByPriceOrderByPrice(float price);
@Query(
"select bookId,bookName,price,author from Book where bookName like :bookname"
)
Object[] queryBook(@Param("bookname") String bookName);
//HQL 語句 select book from Book book where ...
@Query("from Book where bookName like :bookname")
List<Book> queryBooks(@Param("bookname") String bookName);
}接口和實現類
public interface IBookService {
void add(Book book);
void delete(Integer bookId);
Book detail(Integer bookId);
List<Book> queryAll();
void update(Book book);
}package com.wdzl.service.impl;
import com.wdzl.dao.IBookDao;
import com.wdzl.pojo.Book;
import com.wdzl.service.IBookService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Author: zhang
* @Date:2022/8/12
* @Description:
*/
@Service
public class BookService implements IBookService {
@Autowired
private IBookDao bookDao;
@Override
public void add(Book book) {
System.out.println(book.getBookId());
bookDao.save(book); // 注意: 如果對象在數據庫中存在的,執行修改。
System.out.println(book.getBookId());
}
@Override
public void delete(Integer bookId) {
bookDao.deleteById(bookId);
}
@Override
public Book detail(Integer bookId) {
return bookDao.findById(bookId).get();
}
@Override
public List<Book> queryAll() {
return bookDao.findAll();
}
@Override
public void update(Book book) {
//如果對象是存在時,就是修改操作,如果不存在則插入操作
bookDao.save(book);
}
}到這里,就可以使用單元測試來測試 springdata 是否能正常使用了。
頁面必須
1.method必須是post
2.enctype="multipart/form-data" 必須
3.<input type="file"/>必須
static 目錄 下的 add.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Title</title> </head> <body> <!-- 文件上傳時:頁面必須 1.method必須是post 2.enctype="multipart/form-data" 必須 3.<input type="file"> 必須 --> <h3>添加圖書</h3> <form action="add" method="post" enctype="multipart/form-data"> <p>圖書名字:<input name="bookName" /></p> <p>圖書價格:<input name="price" /></p> <p>圖書作者:<input name="author" /></p> <p>出版日期:<input name="pubDate" type="date" /></p> <p>圖書封面:<input name="pic" type="file" /></p> <p><input type="submit" value="保存" /></p> </form> </body> </html>
注意文件上傳處理:單獨上傳、文件名重命名、保存路徑的配置等
package com.wdzl.controller;
import com.wdzl.pojo.Book;
import com.wdzl.service.IBookService;
import com.wdzl.util.FileUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
/**
* @Author: zhang
* @Date:2022/8/12
* @Description:
*
*/
@Controller
public class BookController {
@Autowired
private IBookService bookService;
@Value("${file.upload.savepath}")
private String savePath; //保存文件根目錄
@Value("${file.upload.relativePath}")
private String relativePath;
/**
* 日期處理
* 文件上傳
* @param book
* @return
*/
@PostMapping("add")
public String add(Book book, MultipartFile pic) {
System.out.println("============add()========");
String oriName = pic.getOriginalFilename(); //原始文件命名
//判斷目錄是否存在并創建
File rootDir = new File(savePath);
if (rootDir.exists() == false) {
rootDir.mkdirs();
}
if (!pic.isEmpty()) {
//文件名
String fileName = FileUtils.rename(oriName);
File saveFile = new File(rootDir, fileName);
//轉存到指定文件中
try {
pic.transferTo(saveFile);
System.out.println(">>>>>>文件保存在:" + saveFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
// 文件相對路徑 用來入庫和回顯
fileName = relativePath + fileName;
book.setPicpath(fileName);
}
//入庫
bookService.add(book);
return "redirect:list"; // /list
}
@GetMapping("list")
public String list(ModelMap modelMap) {
List<Book> list = bookService.queryAll();
modelMap.put("booklist", list);
return "list"; ///templates/list.html
}
@GetMapping("detail")
public String detail(Integer bookId, ModelMap modelMap) {
Book book = bookService.detail(bookId);
modelMap.put("book", book);
return "detail";
}
}添加成功后,跳轉到列表頁面顯示,下面使用的 thymeleaf 遍歷顯示
注意:下面圖片路徑、鏈接等處理
templates 下的 list.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>圖書列表</title>
<style type="text/css" rel="stylesheet">
div {
margin: 30px;
text-align: center;
}
</style>
</head>
<body>
<a href="add.html">添加圖書</a>
<hr />
<div>
<table width="75%">
<thead>
<tr bgcolor="#556b2f">
<th>序號</th>
<th>書名</th>
<th>作者</th>
<th>價格</th>
<th>出版日期</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="book,st:${booklist}" th:bgcolor="${st.even?'#aac':''}">
<td th:text="${st.count}"></td>
<td>
<a
th:href="${'detail?bookId='+book.bookId}"
th:text="${book.bookName}"
></a>
</td>
<td th:text="${book.author}"></td>
<td th:text="${book.price}"></td>
<td th:text="${#dates.format(book.pubDate,'yyyy年MM月dd日')}"></td>
<td>
<a th:href="${'del?bookId='+book.bookId}">刪除</a>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>到此,可以通過前端的 add.html 來實現添加和上傳操作了。
注意:默認文件上傳大小是 1M,大于 1M 的會 500 異常。
可以通過配置修改默認文件大小限制:
#文件上傳大小限制 spring.servlet.multipart.max-file-size=2048000
在項目發布運行中,不希望直接顯示 500 異常頁面時,可以配置全局異常解析器來進行處理
異常處理在 springboot 中有多種方式,下面介紹兩種
位置:在啟動類同包及子包下定義類
@ControllerAdvice
public class GlobalExceptionHander {
@ExceptionHandler(Exception.class)
public String doException(Exception ex) { // 不能使用model 無法傳參到頁面顯示
System.out.println(">>>>==異常了:" + ex.toString());
return "error"; // 轉發到 error.html 頁面
}
}上面的 @ControllerAdvice 注解中已經包含 @Component 注解,所以直接會被 spring 掃描加入容器中。
/**
* @Author: zhang
*/
@Configuration
public class ApplicationConfig {
/**
* 全局異常配置
* 頁面可以通過 exception對象來獲取
*/
@Bean
public SimpleMappingExceptionResolver doException() {
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
Properties properties = new Properties();
properties.setProperty("java.lang.Exception", "error"); //映射異常類型和轉發的頁面對應關系
resolver.setExceptionMappings(properties);
System.out.println("===========異常配置======");
return resolver;
}
}上面是一個 @Configuration 標注的配置類。異常對象會被轉發到頁面。
在完成上面的文件上傳和圖書信息添加之后,跳轉到圖書列表頁面,可以通過圖書名鏈接打開圖書詳細信息。
但在顯示圖片靜態資源時,路徑問題導致圖片無法正常顯示。
下面來再來處理下文件上傳和回顯下載或顯示問題
先來回顧上傳時對于圖片保存路徑的設置
首先我們先在配置文件中自定義了兩個路徑:絕對路徑和相對路徑
#上傳的絕對路徑, 文件保存的真正的目錄位置 file.upload.path=d://save/images/ #絕對路徑下的相對路徑 用于前端請求調用的邏輯地址,默認是不能直接使用的 file.upload.relativePath=/images/
在控制器保存圖片時,使用上面地址保存圖片和入庫記錄
@PostMapping("add") //注意這里 pic 需要單獨和頁面元素對應,實體類中只是不同名的字符串用來存地址
public String add(Book book, @ApiParam(value = "圖片文件", required = true)MultipartFile pic){
System.out.println(book+"===="+pic);
String fileName = pic.getOriginalFilename();
//重命名
fileName = FileUtils.rename(fileName);
// 保存到磁盤
File saveDir = new File(savePath); //====================這里是真實保存目錄
if(saveDir.exists()==false){
saveDir.mkdirs();//創建保存圖片的目錄
}
File saveFile = new File(saveDir,fileName);
try {
pic.transferTo(saveFile);
System.out.println("圖片保存在:"+saveFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
//保存的相對路徑
String picPath = relativePath + fileName; //==========這里邏輯目錄 虛擬的
System.out.println(">>>入庫路徑:"+picPath);
book.setPicpath(picPath); //保存到實體類 入庫
//入庫
bookService.add(book);
return "redirect:list";
}首先從上面代碼中可以看到,保存的磁盤的目錄和入庫的路徑是不同的,默認是不對應不能訪問的。
頁面中使用的路徑為數據庫中的相對邏輯路徑
<img th:src="${book.picpath}" width="200" /><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>圖書明細</title>
</head>
<body>
<div>
<p>
<img th:src="${book.picpath}" width="200" />
</p>
<p>書名:<span th:text="${book.bookName}"></span></p>
<p>作者:<span th:text="${book.author}"></span></p>
<p>價格:<span th:text="${book.price}"></span></p>
<p>
出版日期:<span
th:text="${#dates.format(book.pubDate,'yyyy-MM-dd')}"
></span>
</p>
</div>
</body>
</html>如果需要能正常的訪問,則使用下面的配置進行映射
實現 WebMvcConfigurer 同時 標注 @Configuration
/**
* @Author: zhang
* @Date:2022/8/11
* @Description:
*/
@Configuration
public class ApplicationConfig implements WebMvcConfigurer {
@Value("${file.upload.path}")
private String savePath;
@Value("${file.upload.relativePath}")
private String relativePath;
/**
* 資源路徑映射
* 注意:路徑前加 "file:/"
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println(relativePath + "==============" + savePath);
registry
.addResourceHandler(relativePath + "/**")
.addResourceLocations("file:/" + savePath);
}
}通過上面的配置后,再去訪問就可以正常顯示圖片了。
到此,關于“基于SpringBoot怎么實現圖片上傳及圖片回顯”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。