??作者簡介,普修羅雙戰(zhàn)士,一直追求不斷學(xué)習(xí)和成長,在技術(shù)的道路上持續(xù)探索和實踐。
??多年互聯(lián)網(wǎng)行業(yè)從業(yè)經(jīng)驗,歷任核心研發(fā)工程師,項目技術(shù)負(fù)責(zé)人。
??歡迎 ??點贊?評論?收藏
?? SpringBoot 領(lǐng)域知識 ??
鏈接 | 專欄 |
---|---|
SpringBoot 專業(yè)知識學(xué)習(xí)一 | SpringBoot專欄 |
SpringBoot 專業(yè)知識學(xué)習(xí)二 | SpringBoot專欄 |
SpringBoot 專業(yè)知識學(xué)習(xí)三 | SpringBoot專欄 |
SpringBoot 專業(yè)知識學(xué)習(xí)四 | SpringBoot專欄 |
SpringBoot 專業(yè)知識學(xué)習(xí)五 | SpringBoot專欄 |
SpringBoot 專業(yè)知識學(xué)習(xí)六 | SpringBoot專欄 |
SpringBoot 專業(yè)知識學(xué)習(xí)七 | SpringBoot專欄 |
SpringBoot 專業(yè)知識學(xué)習(xí)八 | SpringBoot專欄 |
SpringBoot 專業(yè)知識學(xué)習(xí)九 | SpringBoot專欄 |
本文將詳細(xì)介紹如何在 Spring Boot 中實現(xiàn)文件上傳、下載、刪除功能,采用的技術(shù)框架包括:Spring Boot 2.4.2、Spring MVC、MyBatis 3.5.6、Druid 數(shù)據(jù)源、JUnit 5 等。本文將按照以下步驟一步步實現(xiàn),其中包括:
1. 創(chuàng)建數(shù)據(jù)庫表
2. 配置文件的設(shè)置
3. 實體的創(chuàng)建
4. Mapper 和 DAO 的編寫
5. Service 層的編寫
6. Controller 層的編寫
7. 其他注意事項
8. 實現(xiàn)總結(jié)
在 Spring Boot 中實現(xiàn)文件上傳、下載和刪除功能
1. 創(chuàng)建數(shù)據(jù)庫表
首先,我們需要創(chuàng)建一個用于存儲文件信息的數(shù)據(jù)庫表。在本例中,我們將使用 MySQL 數(shù)據(jù)庫,并創(chuàng)建一個名為 files
的表,包含以下字段:
-
id
:文件的唯一標(biāo)識符,使用自增長主鍵 -
file_name
:文件的名稱 -
file_path
:文件類型 -
file_size
:文件大小 -
path
:存儲文件的文件保存路徑 -
create_time
:文件創(chuàng)建時間
可以使用以下 SQL 語句創(chuàng)建這個表:
CREATE TABLE `file` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '文件ID',
`file_name` varchar(255) NOT NULL COMMENT '文件名',
`file_type` varchar(100) NOT NULL COMMENT '文件類型',
`file_size` varchar(255) NOT NULL COMMENT '文件大小',
`file_path` varchar(255) NOT NULL COMMENT '文件保存路徑',
`create_time` datetime NOT NULL COMMENT '文件創(chuàng)建時間',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='文件存儲表';
2. 配置文件的設(shè)置
在本文中,我們將使用 yml 文件進行配置。首先,我們需要配置數(shù)據(jù)庫的連接信息和 MyBatis 的配置。我們還需要配置上傳文件的路徑和允許上傳的文件大小。以下是在 Spring Boot 應(yīng)用程序中添加配置的示例:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
maxActive: 20
minIdle: 5
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
validationQuery: select 1 from dual
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
filters: stat,wall,log4j,config
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# Mybatis 配置
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.demo.domain
# 文件上傳配置
servlet:
multipart:
enabled: true
max-file-size: 10MB
max-request-size: 100MB
location: /data/file-server/
其中,datasource 部分是數(shù)據(jù)庫連接信息的配置。Mybatis 部分配置了 Mybatis 的映射文件和實體類的位置。servlet 部分用于配置上傳文件的大小和位置。
3. 實體的創(chuàng)建
在本文中,我們將創(chuàng)建 FileEntity 實體類,作為對文件信息的模型。以下是 FileEntity 類的示例:
@Data
public class FileEntity {
private Integer id;
private String name;
private Long size;
private String type;
private String path;
// 下面為 getter 和 setter 方法
}
注意,我們?yōu)槊總€字段添加了 getter 和 setter 方法,以便可以從數(shù)據(jù)庫中讀取和寫入文件信息。
4. Mapper 和 DAO 的編寫
在編寫 Mapper 和 DAO 之前,我們需要在 pom.xml 文件中引入 Mybatis 和 Druid。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
創(chuàng)建 Mapper 接口和 XML 文件,使用 Mybatis 注解或 SQL 語句與數(shù)據(jù)庫進行交互。
為了實現(xiàn)上傳、下載、刪除功能,我們可能需要使用一些第三方包或工具類。以下是一個簡單的基于Spring Boot的mapper示例,演示了如何使用七牛云存儲實現(xiàn)上傳、下載、刪除文件:
import java.io.File;
import java.io.IOException;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.BucketManager;
import com.qiniu.common.QiniuException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class FileManager {
@Value("${qiniu.accessKey}")
private String accessKey;
@Value("${qiniu.secretKey}")
private String secretKey;
@Value("${qiniu.bucket}")
private String bucket;
@Value("${qiniu.basePath}")
private String basePath;
private Auth auth;
private Configuration cfg;
private UploadManager uploadManager;
private BucketManager bucketManager;
public FileManager() {
auth = Auth.create(accessKey, secretKey);
cfg = new Configuration(Region.autoRegion());
uploadManager = new UploadManager(cfg);
bucketManager = new BucketManager(auth, cfg);
}
/**
* 上傳本地文件到七牛云
*/
public String uploadFile(String filePath, String fileName) {
String key = basePath + fileName;
try {
Response res = uploadManager.put(filePath, key, auth.uploadToken(bucket), null, null);
DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
return putRet.hash;
} catch (QiniuException e) {
return null;
}
}
/**
* 根據(jù)文件名從七牛云刪除文件
*/
public boolean deleteFile(String fileName) {
try {
bucketManager.delete(bucket, basePath + fileName);
return true;
} catch (QiniuException ex) {
return false;
}
}
/**
* 根據(jù)文件名從七牛云獲取文件信息
*/
public FileInfo getFileInfo(String fileName) {
try {
return bucketManager.stat(bucket, basePath + fileName);
} catch (QiniuException ex) {
return null;
}
}
/**
* 根據(jù)文件名從七牛云下載文件到本地
*/
public boolean downloadFile(String fileName, String localFilePath) {
try {
bucketManager.download(bucket, basePath + fileName, new File(localFilePath));
return true;
} catch (QiniuException ex) {
return false;
}
}
}
這個示例利用了七牛云存儲服務(wù)完成文件的上傳、下載和刪除操作。關(guān)鍵在于使用了七牛云存儲提供的Java SDK,在代碼中我們通過使用該SDK的函數(shù)實現(xiàn)對云上文件的操作。同時,我們需要在我們的Spring Boot項目中配置七牛云存儲服務(wù)的 accessKey
、secretKey
和 bucket
等參數(shù)。具體使用方法可以參照七牛云存儲官方文檔進行配置和使用。
5. Service 層的編寫
5.1 接口層代碼實現(xiàn)邏輯
public interface StorageService {
String save(MultipartFile file);
Resource load(String filename);
void delete(String filename);
}
5.2 接口實現(xiàn)層代碼實現(xiàn)邏輯
@Service
public class LocalStorageService implements StorageService {
private final Path storageLocation;
@Autowired
public LocalStorageService(@Value("${spring.servlet.multipart.location}") String storageLocation) {
this.storageLocation = Paths.get(storageLocation);
}
@Override
public String save(MultipartFile file) {
// 實現(xiàn)文件保存的業(yè)務(wù)邏輯,如將文件保存到本地文件系統(tǒng)
// 返回文件保存后的路徑或 URL
String filename = file.getOriginalFilename();
Path targetLocation = this.storageLocation.resolve(filename);
try {
file.transferTo(targetLocation);
return targetLocation.toString();
} catch (IOException e) {
throw new RuntimeException("Failed to save file: " + filename, e);
}
}
@Override
public Resource load(String filename) {
// 實現(xiàn)文件加載的業(yè)務(wù)邏輯,如從本地文件系統(tǒng)讀取文件并返回
Path file = this.storageLocation.resolve(filename);
Resource resource;
try {
resource = new UrlResource(file.toUri());
} catch (MalformedURLException e) {
throw new RuntimeException("Failed to load file: " + filename, e);
}
if (resource.exists() && resource.isReadable()) {
return resource;
} else {
throw new RuntimeException("File not found: " + filename);
}
}
@Override
public void delete(String filename) {
// 實現(xiàn)文件刪除的業(yè)務(wù)邏輯,如從本地文件系統(tǒng)刪除文件
Path file = this.storageLocation.resolve(filename);
try {
Files.delete(file);
} catch (IOException e) {
throw new RuntimeException("Failed to delete file: " + filename, e);
}
}
}
6. Controller 層的編寫
創(chuàng)建文件上傳控制器類,用于處理文件上傳、下載和刪除請求:
@RestController
public class FileController {
@Autowired
private StorageService storageService;
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
// 調(diào)用 storageService.save(file) 進行文件保存的業(yè)務(wù)邏輯
// 返回處理結(jié)果,如文件的 URL 或保存路徑等
String filePath = storageService.save(file);
return "File uploaded successfully!";
}
@GetMapping("/download/{filename}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
// 調(diào)用 storageService.load(filename) 進行文件下載的業(yè)務(wù)邏輯
// 創(chuàng)建 Resource 對象,將文件流作為響應(yīng)體返回
Resource fileResource = storageService.load(filename);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
.body(fileResource);
}
@DeleteMapping("/delete/{filename}")
public String deleteFile(@PathVariable String filename) {
// 調(diào)用 storageService.delete(filename) 進行文件刪除的業(yè)務(wù)邏輯
storageService.delete(filename);
return "File deleted successfully!";
}
}
7. 其他注意事項
除了上述提到的注意事項之外,實現(xiàn)文件上傳、下載和刪除功能時還應(yīng)注意以下幾點:
7.1 文件大小限制: 為了避免惡意用戶上傳過大的文件導(dǎo)致服務(wù)器資源耗盡,應(yīng)該 對上傳文件的大小進行限制
。你可以在application.yml
中使用以下配置設(shè)置上傳文件的最大大?。▎挝粸樽止?jié)):
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
maxActive: 20
minIdle: 5
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
validationQuery: select 1 from dual
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
filters: stat,wall,log4j,config
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# Mybatis 配置
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.demo.domain
# 文件上傳配置
servlet:
multipart:
enabled: true
max-file-size: 10MB
max-request-size: 100MB
location: /data/file-server/
在上述示例中,文件最大大小被限制為10MB。你可以根據(jù)需要進行調(diào)整。
7.2 文件類型限制: 在文件上傳時,你可以通過文件的擴展名或MIME類型進行檢查,以確保只接受指定類型的文件。例如,你可以使用Java的正則表達式或Apache Tika等庫來驗證文件的擴展名或MIME類型。
7.3 安全性考慮: 文件上傳功能可能會面臨一些安全威脅,如 文件包含漏洞(如路徑遍歷攻擊)、惡意文件上傳或執(zhí)行
,你應(yīng)該采取相應(yīng)的安全措施來防止這些威脅。例如,可以對文件名進行過濾,禁止某些關(guān)鍵詞,或者對上傳的文件進行殺毒掃描。
7.4 跨域請求問題: 當(dāng)實現(xiàn)文件上傳、下載和刪除功能時,你可能會遇到 跨域請求
問題。如果你的前端應(yīng)用與后端應(yīng)用分別部署在不同的域中,你需要在后端應(yīng)用中進行跨域配置,以允許來自其他域的請求。
7.5 文件存儲策略: 對于大規(guī)模的文件上傳和下載應(yīng)用,僅僅保存文件到本地可能不夠有效或可擴展。你可以考慮使用云存儲服務(wù)(如Amazon S3、阿里云OSS)或分布式文件系統(tǒng)(如GlusterFS、Ceph等)來存儲和管理上傳的文件。
7.6 異步處理: 對于大文件上傳或下載的情況,可以考慮使用異步處理來提高性能和用戶體驗。你可以利用Spring Boot的異步特性(如@Async
注解和DeferredResult
對象)來實現(xiàn)異步處理。
在實現(xiàn)文件上傳、下載和刪除功能時,以上是一些常見的注意事項。根據(jù)你的具體需求和應(yīng)用背景,可能還有其他的注意事項需要注意。希望這些信息能對你有所幫助。如果有更多問題,請隨時提問。
8. 實現(xiàn)總結(jié)
通過完成上述步驟,我們成功實現(xiàn)了在 Spring Boot 中的文件上傳、下載和刪除功能,包括創(chuàng)建數(shù)據(jù)庫表、文件上傳功能、文件下載功能和文件刪除功能。
在實現(xiàn)這些功能時,我們還學(xué)習(xí)了一些重要的注意事項。例如,在文件上傳時,需要確保保存文件的目錄存在;在文件下載和刪除時,需要確保文件存在。
綜上所述,Spring Boot 提供了強大的工具和簡化的方式來實現(xiàn)文件上傳、下載和刪除功能,使我們能夠輕松地構(gòu)建功能完善的 Web 應(yīng)用程序。這些功能可以滿足實際項目中的需求,為用戶提供便捷的文件操作體驗。文章來源:http://www.zghlxwxcb.cn/news/detail-803549.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-803549.html
到了這里,關(guān)于Spring Boot 中實現(xiàn)文件上傳、下載、刪除功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!