欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot中實現(xiàn)文件上傳、下載、刪除功能的步驟

 更新時間:2024年01月16日 09:28:20   作者:普修羅雙戰(zhàn)士  
本文將詳細介紹如何在 Spring Boot 中實現(xiàn)文件上傳、下載、刪除功能,采用的技術(shù)框架包括:Spring Boot 2.4.2、Spring MVC、MyBatis 3.5.6、Druid 數(shù)據(jù)源、JUnit 5 等,文中有詳細的操作步驟和示例代碼供大家參考,需要的朋友可以參考下

在 Spring Boot 中實現(xiàn)文件上傳、下載和刪除功能

1. 創(chuàng)建數(shù)據(jù)庫表

首先,我們需要創(chuàng)建一個用于存儲文件信息的數(shù)據(jù)庫表。在本例中,我們將使用 MySQL 數(shù)據(jù)庫,并創(chuàng)建一個名為 files 的表,包含以下字段:

  • id:文件的唯一標識符,使用自增長主鍵
  • 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 跨域請求問題: 當實現(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)用背景,可能還有其他的注意事項需要注意。希望這些信息能對你有所幫助。如果有更多問題,請隨時提問。

實現(xiàn)總結(jié)

通過完成上述步驟,我們成功實現(xiàn)了在 Spring Boot 中的文件上傳、下載和刪除功能,包括創(chuàng)建數(shù)據(jù)庫表、文件上傳功能、文件下載功能和文件刪除功能。

在實現(xiàn)這些功能時,我們還學習了一些重要的注意事項。例如,在文件上傳時,需要確保保存文件的目錄存在;在文件下載和刪除時,需要確保文件存在。

綜上所述,Spring Boot 提供了強大的工具和簡化的方式來實現(xiàn)文件上傳、下載和刪除功能,使我們能夠輕松地構(gòu)建功能完善的 Web 應(yīng)用程序。這些功能可以滿足實際項目中的需求,為用戶提供便捷的文件操作體驗。

以上就是SpringBoot中實現(xiàn)文件上傳、下載、刪除功能的步驟的詳細內(nèi)容,更多關(guān)于SpringBoot實現(xiàn)文件上傳、下載、刪除的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Spring @Value的注解使用和原理解析

    Spring @Value的注解使用和原理解析

    @Value注解在Spring開發(fā)中是一個使用很頻繁的注解,在項目開發(fā)中,我們通常需要讀取配置文件中的一些信息,當然,@Value不單單能讀取配置文件,還能讀取系統(tǒng)屬性,還可以讀取其他bean的屬性,本章就來詳細介紹@Value注解的使用和對源碼進行分析
    2023-06-06
  • java使用WatchService監(jiān)控文件夾示例

    java使用WatchService監(jiān)控文件夾示例

    本篇文章主要介紹了java使用WatchService監(jiān)控文件夾示例的資料,這里整理了詳細的代碼,有需要的小伙伴可以參考下。
    2017-02-02
  • java.lang.ClassCastException的問題解決

    java.lang.ClassCastException的問題解決

    本文主要介紹了java.lang.ClassCastException的問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-06-06
  • 關(guān)于SpringBoot的自動裝配原理詳解

    關(guān)于SpringBoot的自動裝配原理詳解

    這篇文章主要介紹了關(guān)于SpringBoot的自動裝配原理詳解,Spring?Boot自動裝配原理是指Spring?Boot在啟動時自動掃描項目中的依賴關(guān)系,根據(jù)依賴關(guān)系自動配置相應(yīng)的Bean,從而簡化了Spring應(yīng)用的配置過程,需要的朋友可以參考下
    2023-07-07
  • 談?wù)剬ava中的volatile的理解

    談?wù)剬ava中的volatile的理解

    這篇文章主要介紹了對Java中的volatile的理解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-11-11
  • Java開發(fā)SpringBoot集成接口文檔實現(xiàn)示例

    Java開發(fā)SpringBoot集成接口文檔實現(xiàn)示例

    這篇文章主要為大家介紹了Java開發(fā)SpringBoot如何集成接口文檔的實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步
    2021-10-10
  • java之a(chǎn)ssert關(guān)鍵字用法案例詳解

    java之a(chǎn)ssert關(guān)鍵字用法案例詳解

    這篇文章主要介紹了java之a(chǎn)ssert關(guān)鍵字用法案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • springboot+jwt+微信小程序授權(quán)登錄獲取token的方法實例

    springboot+jwt+微信小程序授權(quán)登錄獲取token的方法實例

    本文主要介紹了springboot+jwt+微信小程序授權(quán)登錄獲取token的方法實例,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • 詳解commons-pool2池化技術(shù)

    詳解commons-pool2池化技術(shù)

    本文主要是分析commons-pool2池化技術(shù)的實現(xiàn)方案,希望通過本文能讓讀者對commons-pool2的實現(xiàn)原理一個更全面的了解
    2021-06-06
  • Java實現(xiàn)讀取文章中重復(fù)出現(xiàn)的中文字符串

    Java實現(xiàn)讀取文章中重復(fù)出現(xiàn)的中文字符串

    本文主要介紹了Java實現(xiàn)讀取文章中重復(fù)出現(xiàn)的中文字符串的方法。具有很好的參考價值。下面跟著小編一起來看下吧
    2017-03-03

最新評論