基于SpringBoot框架實現(xiàn)文件上傳下載分享功能
SpringBoot 文件上傳下載是我們常用的功能,比如圖片、視頻上傳、下載和更新等功能的實現(xiàn)。下面我們詳細(xì)分析一下:
1、pom.xml包引入
<!-- 基礎(chǔ) web 依賴(包含文件上傳支持) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 文件操作工具類 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>2、存儲目錄設(shè)計
/data/project_files/
├── images/
│ ├── 202405/
│ └── 202406/
└── videos/
├── 202405/
└── 202406/- 使用 UUID 生成唯一文件名(保留原始擴展名)
- 按年月生成子目錄(防止單目錄文件過多)
- 推薦存儲絕對路徑到數(shù)據(jù)庫(如:/images/202405/uuid123.jpg)
3、配置文件信息
# win環(huán)境文件存儲根目錄 file.upload-dir=D:/data/project_files/ #linux環(huán)境 file.upload-dir=/data/project_files/ # 上傳大小限制(默認(rèn)1MB,按需調(diào)整) spring.servlet.multipart.max-file-size=100MB spring.servlet.multipart.max-request-size=100MB
4、上傳接口
@PostMapping("/upload")
public ApiResult uploadFile(@RequestParam("file") MultipartFile file,
@RequestParam String fileType) throws IOException {
// 驗證文件類型
if (!Arrays.asList("image", "video").contains(fileType)) {
return ApiResult.error("Invalid file type");
}
// 生成存儲路徑
String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
String fileExt = FilenameUtils.getExtension(file.getOriginalFilename());
String uuid = UUID.randomUUID().toString();
String relativePath = String.format("/%s/%s/%s.%s",
fileType + "s", datePath, uuid, fileExt);
// 保存文件
File dest = new File(uploadDir + relativePath);
FileUtils.forceMkdirParent(dest);
file.transferTo(dest);
return ApiResult.ok(relativePath);
}直接獲取下載地址上傳方式
@PostMapping("/uploadFile")
@ApiOperation(value="文件上傳",notes = "文件上傳-√")
public String uploadFile(@RequestParam("file")MultipartFile file, @RequestParam String fileType) throws IOException {
// 驗證文件類型
if (!Arrays.asList("image", "video").contains(fileType)) {
return CommonResponse.buildErrorResponse("Error file type");
}
// 生成存儲路徑
String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
String fileExt = FilenameUtils.getExtension(file.getOriginalFilename());
String uuid = UUID.randomUUID().toString();
String relativePath = String.format("/%s/%s/%s.%s",
fileType + "s", datePath, uuid, fileExt);
// 保存文件
File dest = new File(uploadDir + relativePath);
FileUtils.forceMkdirParent(dest);
file.transferTo(dest);
log.info("filePath:{}",fileIpPortUrl+relativePath);
return (fileIpPortUrl+relativePath);
}5、下載接口
1)接口下載
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam String filePath) throws IOException {
Path path = Paths.get(uploadDir + filePath);
Resource resource = new UrlResource(path.toUri());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}2)原路徑獲取下載
@GetMapping("/download/**")
@ApiOperation(value="文件下載接口",notes = "文件下載接口-√")
public ResponseEntity<Resource> downloadFile(HttpServletRequest request) throws IOException {
// 獲取完整文件路徑(需截掉前綴路徑)
String filePath = request.getServletPath()
.replaceFirst("/file/******/", "");
log.info("filePath:{}",filePath);
// 路徑安全校驗
if (filePath.contains("..")) {
return ResponseEntity.badRequest().build();
}
Path path = Paths.get(uploadDir + File.separator + filePath);
log.info("path:{}",path);
Resource resource = new UrlResource(path.toUri());
log.info("toUri:{}",path.toUri());
if (!resource.exists()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}6、修改文件
@PostMapping("/update")
public ApiResult updateFile(@RequestParam("file") MultipartFile file,
@RequestParam String oldFilePath) throws IOException {
// 刪除舊文件
File oldFile = new File(uploadDir + oldFilePath);
if (oldFile.exists()) {
FileUtils.forceDelete(oldFile);
}
// 上傳新文件(復(fù)用上傳邏輯)
return uploadFile(file, parseFileType(oldFilePath));
}或者
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.UUID;
@PostMapping("/update")
public String updateFile(@RequestParam("file") MultipartFile file,
@RequestParam String oldFilePath, @RequestParam String fileType) throws IOException {
// 刪除舊文件
File oldFile = new File(uploadDir + oldFilePath);
if (oldFile.exists()) {
FileUtils.forceDelete(oldFile);
}
// 上傳新文件(復(fù)用上傳邏輯)
return uploadFile(file, fileType);
}到此,文件上傳下載分享完成。
到此這篇關(guān)于基于SpringBoot框架實現(xiàn)文件上傳下載分享功能的文章就介紹到這了,更多相關(guān)SpringBoot文件上傳下載分享內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot整合RestTemplate用法的實現(xiàn)
本篇主要介紹了RestTemplate中的GET,POST,PUT,DELETE、文件上傳和文件下載6大常用的功能,具有一定的參考價值,感興趣的可以了解一下2023-08-08
SpringBoot框架aop切面的execution表達式解讀
這篇文章主要介紹了SpringBoot框架aop切面的execution表達式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
springboot?pom文件加入監(jiān)控依賴后沒有起作用的解決
這篇文章主要介紹了springboot?pom文件加入監(jiān)控依賴后沒有起作用的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
java線程池ThreadPoolExecutor的八種拒絕策略示例詳解
ThreadPoolExecutor是一個典型的緩存池化設(shè)計的產(chǎn)物,因為池子有大小,當(dāng)池子體積不夠承載時,就涉及到拒絕策略。JDK中已預(yù)設(shè)了?4?種線程池拒絕策略,下面結(jié)合場景詳細(xì)聊聊這些策略的使用場景以及還能擴展哪些拒絕策略2021-11-11

