源碼在最下面
思路
- 一般情況下都是將用戶上傳的圖片放到服務器的某個文件夾中,然後將圖片在服務器的路徑存入數據庫。
- 由於用戶自己保存的圖片文件名可能跟其他用戶同名造成衝突,因此本Demo選擇了使用UUID來生成隨機的文件名解決衝突。
但是本Demo不涉及任何有關數據庫的操作,便於演示、學習。
步驟
自動創建spring boot 項目 (已經有項目就不用看這步了)
- 點擊“Switch to the full version.”可參考下圖所示:
然後解壓 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>