基于SpringBoot實(shí)現(xiàn)圖片上傳與顯示
本文為大家分享了SpringBoot實(shí)現(xiàn)圖片上傳與顯示的具體代碼,供大家參考,具體內(nèi)容如下
SpringBoot實(shí)現(xiàn)圖片上傳與顯示:Demo地址
效果圖預(yù)覽

思路
- 一般情況下都是將用戶上傳的圖片放到服務(wù)器的某個(gè)文件夾中,然后將圖片在服務(wù)器中的路徑存入數(shù)據(jù)庫(kù)。本Demo也是這樣做的。
- 由于用戶自己保存的圖片文件名可能跟其他用戶同名造成沖突,因此本Demo選擇了使用UUID來(lái)生成隨機(jī)的文件名解決沖突。
- 但是本Demo不涉及任何有關(guān)數(shù)據(jù)庫(kù)的操作,便于演示,就用原來(lái)的文件名。
步驟
pom相關(guān)依賴
- 基于Spring boot當(dāng)然是繼承了spring boot這不用多說(shuō)
- 具體依賴,主要是FreeMarker相關(guān)依賴為了展現(xiàn)頁(yè)面,習(xí)慣用JSP也可以添加JSP的依賴,只是為了展示頁(yè)面,這個(gè)不重要。
<dependencies> <!--FreeMarker模板視圖依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
application.properties相關(guān)配置
除了視圖模板相關(guān)的配置,重點(diǎn)是要配置一下文件上傳的內(nèi)存大小和文件上傳路徑
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 #設(shè)置面板后綴 spring.freemarker.suffix=.ftl # 設(shè)置單個(gè)文件最大內(nèi)存 multipart.maxFileSize=50Mb # 設(shè)置所有文件最大內(nèi)存 multipart.maxRequestSize=50Mb # 自定義文件上傳路徑 web.upload-path=E:/Develop/Files/Photos/
生成文件名
不準(zhǔn)備生成文件名的可以略過(guò)此步驟
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;
/**
* 跳轉(zhuǎn)到文件上傳頁(yè)面
* @return
*/
@RequestMapping("test")
public String toUpload(){
return "test";
}
/**
*
* @param file 要上傳的文件
* @return
*/
@RequestMapping("fileUpload")
public String upload(@RequestParam("fileName") MultipartFile file, Map<String, Object> map){
// 要上傳的目標(biāo)文件存放路徑
String localPath = "E:/Develop/Files/Photos";
// 上傳成功或者失敗的提示
String msg = "";
if (FileUtils.upload(file, localPath, file.getOriginalFilename())){
// 上傳成功,給出頁(yè)面提示
msg = "上傳成功!";
}else {
msg = "上傳失?。?;
}
// 顯示圖片
map.put("msg", msg);
map.put("fileName", file.getOriginalFilename());
return "forward:/test";
}
/**
* 顯示單張圖片
* @return
*/
@RequestMapping("show")
public ResponseEntity showPhotos(String fileName){
try {
// 由于是讀取本機(jī)的文件,file是一定要加上的, path是在application配置文件中的路徑
return ResponseEntity.ok(resourceLoader.getResource("file:" + path + fileName));
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
}
頁(yè)面
頁(yè)面主要是from表單和下面的 <img src="/show?fileName=${fileName}" /> ,其余都是細(xì)節(jié)。
<!DOCTYPE html>
<head>
<meta charset="UTF-8" />
<title>圖片上傳Demo</title>
</head>
<body>
<h1 >圖片上傳Demo</h1>
<form action="fileUpload" method="post" enctype="multipart/form-data">
<p>選擇文件: <input type="file" name="fileName"/></p>
<p><input type="submit" value="提交"/></p>
</form>
<#--判斷是否上傳文件-->
<#if msg??>
<span>${msg}</span><br>
<#else >
<span>${msg!("文件未上傳")}</span><br>
</#if>
<#--顯示圖片,一定要在img中的src發(fā)請(qǐng)求給controller,否則直接跳轉(zhuǎn)是亂碼-->
<#if fileName??>
<img src="/show?fileName=${fileName}" style="width: 200px"/>
<#else>
<img src="/show" style="width: 100px"/>
</#if>
</body>
</html>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合ElasticSearch實(shí)踐
本篇文章主要介紹了SpringBoot整合ElasticSearch實(shí)踐,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05
SpringBoot使用Maven插件進(jìn)行項(xiàng)目打包的方法
這篇文章主要介紹了SpringBoot使用Maven插件進(jìn)行項(xiàng)目打包的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
java簡(jiǎn)單實(shí)現(xiàn)數(shù)組的增刪改查方法
這篇文章主要介紹了Java數(shù)組的增刪改查的示例,幫助大家更好的利用Java處理數(shù)據(jù),感興趣的朋友可以了解下,希望能給你帶來(lái)幫助2021-07-07
Spring Cloud Consul的服務(wù)注冊(cè)與發(fā)現(xiàn)
這篇文章主要介紹了Spring Cloud Consul服務(wù)注冊(cè)與發(fā)現(xiàn)的實(shí)現(xiàn)方法,幫助大家更好的理解和學(xué)習(xí)使用spring框架,感興趣的朋友可以了解下2021-02-02
Java服務(wù)器主機(jī)信息監(jiān)控工具類的示例代碼
這篇文章主要介紹了Java服務(wù)器主機(jī)信息監(jiān)控工具類的示例代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
關(guān)于使用Mybatisplus自帶的selectById和insert方法時(shí)的一些問(wèn)題
這篇文章主要介紹了關(guān)于使用Mybatisplus自帶的selectById和insert方法時(shí)的一些問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08

