基於SpringBoot的圖片上傳到伺服器+顯示(附帶原始碼)
阿新 • • 發佈:2019-02-02
原始碼在最下面
思路
- 一般情況下都是將使用者上傳的圖片放到伺服器的某個資料夾中,然後將圖片在伺服器的路徑存入資料庫。
- 由於使用者自己儲存的圖片檔名可能跟其他使用者同名造成衝突,因此本Demo選擇了使用UUID來生成隨機的檔名解決衝突。
但是本Demo不涉及任何有關資料庫的操作,便於演示、學習。
步驟
自動建立spring boot 專案 (已經有專案就不用看這步了)
然後解壓 import (Maven Projects型別)到MyEclipse(看你使用什麼工具啦)中
pom相關依賴 (也應該是springboot必備依賴了)
<!--web -->
<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>
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<!-- thymeleaf end -->
application.properties相關配置
#配置靜態資源前後綴
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
# 設定單個檔案最大記憶體
multipart.maxFileSize=50Mb
# 設定所有檔案最大記憶體
multipart.maxRequestSize=50Mb
# 自定義檔案上傳路徑
web.upload-path=D:/image/
生成檔名(不準備生成檔名的可以略過此步驟)
package com.example.utils;
import java.util.UUID;
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);
}
}
package com.example.utils;
import java.util.UUID;
public class UUIDUtils {
public static String getUUID(){
return UUID.randomUUID().toString().replace("-", "");
}
}
檔案上傳工具類
package com.example.utils;
import java.io.File;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
/**
*
* @author gaoxuyang
*
*/
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) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
Controller
package com.example.Controller;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.example.utils.FileUtils;
/**
* @author gaoxuyang
*@user 圖片上傳及顯示
*/
@Controller
public class FileUploadController {
private final ResourceLoader resourceLoader;
@Autowired
public FileUploadController(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Value("${web.upload-path}")
private String path;
/**
* @return 跳轉到檔案上傳頁面
*/
@RequestMapping("/Demo")
public String index(){
return "Dome";
}
/**
*
* @return 跳轉到檔案顯示頁面
*/
@RequestMapping("/show")
public String show(){
return "show";
}
/**
*
* @param file 上傳的檔案
* @return
*/
@ResponseBody
@RequestMapping("/fileUpload")
public String upload(@RequestParam("file")MultipartFile file ){
//1定義要上傳檔案 的存放路徑
String localPath="D:/image";
//2獲得檔名字
String fileName=file.getOriginalFilename();
//2上傳失敗提示
String warning="";
if(FileUtils.upload(file, localPath, fileName)){
//上傳成功
warning="上傳成功";
}else{
warning="上傳失敗";
}
System.out.println(warning);
return "上傳成功";
}
/**
* 顯示圖片
* @param fileName 檔名
* @return
*/
@RequestMapping("show")
public ResponseEntity show(String fileName){
try {
// 由於是讀取本機的檔案,file是一定要加上的, path是在application配置檔案中的路徑
return ResponseEntity.ok(resourceLoader.getResource("file:" + path + fileName));
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
}
頁面
- 頁面我寫了兩個頁面一個上傳一個顯示,顯示頁面是寫死的,你可以根據自己需要動態獲得
- 上傳
<body>
<form action="fileUpload" method="post" enctype="multipart/form-data">
<p>選擇檔案:<input type="file" name="file" /></p>
<p><input type="submit" value="提交"/></p>
</form>
</body>
- 顯示
<body>
<div>
<!-- 圖片位置動態顯示你要顯示的圖片 這裡是寫死的-->
<img src="/show?fileName=2.JPG" style="width: 200px"/>
</div>
</body>