Demo地址
https://github.com/HelloSummer5/FileUploadDemo
效果圖預覽
思路
- 一般情況下都是將用戶上傳的圖片放到服務器的某個文件夾中,然后將圖片在服務器中的路徑存入數(shù)據(jù)庫昏名。本Demo也是這樣做的涮雷。
- 由于用戶自己保存的圖片文件名可能跟其他用戶同名造成沖突,因此本Demo選擇了使用UUID來生成隨機的文件名解決沖突轻局。
- 但是本Demo不涉及任何有關數(shù)據(jù)庫的操作洪鸭,便于演示样刷,就用原來的文件名。
步驟
pom相關依賴
- 基于Spring boot當然是繼承了spring boot這不用多說
- 具體依賴卿嘲,主要是FreeMarker相關依賴為了展現(xiàn)頁面颂斜,習慣用JSP也可以添加JSP的依賴,只是為了展示頁面拾枣,這個不重要沃疮。
<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相關配置
- 除了視圖模板相關的配置,重點是要配置一下文件上傳的內(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
#設置面板后綴
spring.freemarker.suffix=.ftl
# 設置單個文件最大內(nèi)存
multipart.maxFileSize=50Mb
# 設置所有文件最大內(nèi)存
multipart.maxRequestSize=50Mb
# 自定義文件上傳路徑
web.upload-path=E:/Develop/Files/Photos/
生成文件名
- 不準備生成文件名的可以略過此步驟
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;
/**
* 跳轉到文件上傳頁面
* @return
*/
@RequestMapping("test")
public String toUpload(){
return "test";
}
/**
*
* @param file 要上傳的文件
* @return
*/
@RequestMapping("fileUpload")
public String upload(@RequestParam("fileName") MultipartFile file, Map<String, Object> map){
// 要上傳的目標文件存放路徑
String localPath = "E:/Develop/Files/Photos";
// 上傳成功或者失敗的提示
String msg = "";
if (FileUtils.upload(file, localPath, file.getOriginalFilename())){
// 上傳成功司蔬,給出頁面提示
msg = "上傳成功!";
}else {
msg = "上傳失斠毯俊啼!";
}
// 顯示圖片
map.put("msg", msg);
map.put("fileName", file.getOriginalFilename());
return "forward:/test";
}
/**
* 顯示單張圖片
* @return
*/
@RequestMapping("show")
public ResponseEntity showPhotos(String fileName){
try {
// 由于是讀取本機的文件,file是一定要加上的左医, path是在application配置文件中的路徑
return ResponseEntity.ok(resourceLoader.getResource("file:" + path + fileName));
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
}
頁面
- 頁面主要是from表單和下面的
<img src="/show?fileName=${fileName}" />
授帕,其余都是細節(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ā)請求給controller跛十,否則直接跳轉是亂碼-->
<#if fileName??>
<img src="/show?fileName=${fileName}" style="width: 200px"/>
<#else>
<img src="/show" style="width: 100px"/>
</#if>
</body>
</html>