亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

基于SpringBoot框架實現(xiàn)文件上傳下載分享功能

 更新時間:2025年06月08日 08:40:39   作者:寅燈  
在當(dāng)今的Web應(yīng)用開發(fā)中,文件上傳與下載功能是極為常見且重要的需求,無論是用戶上傳頭像、分享文檔,還是系統(tǒng)生成報告供用戶下載,都離不開這一功能模塊,SpringBoot作為一款流行的Java開發(fā)框架,為我們提供了簡潔高效的方式來實現(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)

    SpringBoot整合RestTemplate用法的實現(xiàn)

    本篇主要介紹了RestTemplate中的GET,POST,PUT,DELETE、文件上傳和文件下載6大常用的功能,具有一定的參考價值,感興趣的可以了解一下
    2023-08-08
  • Java實現(xiàn)多任務(wù)執(zhí)行助手

    Java實現(xiàn)多任務(wù)執(zhí)行助手

    這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)多任務(wù)執(zhí)行助手,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • SpringBoot框架aop切面的execution表達式解讀

    SpringBoot框架aop切面的execution表達式解讀

    這篇文章主要介紹了SpringBoot框架aop切面的execution表達式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • SpringBoot使用@Async注解處理異步事件的方法

    SpringBoot使用@Async注解處理異步事件的方法

    在現(xiàn)代應(yīng)用程序中,異步編程已經(jīng)成為了必備的技能,異步編程使得應(yīng)用程序可以同時處理多個請求,從而提高了應(yīng)用程序的吞吐量和響應(yīng)速度,在SpringBoot 中,我們可以使用 @Async 注解來實現(xiàn)異步編程,本文將介紹 @Async 注解的使用方法和注意事項
    2023-09-09
  • SpringBoot之Profile的兩種使用方式詳解

    SpringBoot之Profile的兩種使用方式詳解

    當(dāng)在不同的環(huán)境下,想通過修改配置文件來連接不同的數(shù)據(jù)庫,比如在開發(fā)過程中啟動項目時,想連接開發(fā)環(huán)境對應(yīng)的數(shù)據(jù)庫,可以在配置文件中指定environment=dev,其他環(huán)境類似,此時就需要用到Spring為我們提供的Profile功能,本文給大家介紹了SpringBoot之Profile的兩種使用方式
    2024-10-10
  • springboot?pom文件加入監(jiān)控依賴后沒有起作用的解決

    springboot?pom文件加入監(jiān)控依賴后沒有起作用的解決

    這篇文章主要介紹了springboot?pom文件加入監(jiān)控依賴后沒有起作用的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • idea 列編輯模式取消的操作

    idea 列編輯模式取消的操作

    這篇文章主要介紹了idea 列編輯模式取消的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • 由淺入深快速掌握J(rèn)ava?數(shù)組的使用

    由淺入深快速掌握J(rèn)ava?數(shù)組的使用

    Java?數(shù)組?數(shù)組對于每一門編程語言來說都是重要的數(shù)據(jù)結(jié)構(gòu)之一,當(dāng)然不同語言對數(shù)組的實現(xiàn)及處理也不盡相同。?Java?語言中提供的數(shù)組是用來存儲固定大小的同類型元素
    2022-04-04
  • JAVA通過XPath解析XML性能比較詳解

    JAVA通過XPath解析XML性能比較詳解

    本篇文章主要介紹了JAVA通過XPath解析XML性能比較詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-02-02
  • java線程池ThreadPoolExecutor的八種拒絕策略示例詳解

    java線程池ThreadPoolExecutor的八種拒絕策略示例詳解

    ThreadPoolExecutor是一個典型的緩存池化設(shè)計的產(chǎn)物,因為池子有大小,當(dāng)池子體積不夠承載時,就涉及到拒絕策略。JDK中已預(yù)設(shè)了?4?種線程池拒絕策略,下面結(jié)合場景詳細(xì)聊聊這些策略的使用場景以及還能擴展哪些拒絕策略
    2021-11-11

最新評論