最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

SpringBoot 文件上傳下載是我們常用的功能,比如圖片、視頻上傳、下載和更新等功能的實(shí)現(xiàn)。下面我們?cè)敿?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、存儲(chǔ)目錄設(shè)計(jì)

/data/project_files/
    ├── images/
    │   ├── 202405/
    │   └── 202406/
    └── videos/
        ├── 202405/
        └── 202406/
  • 使用 UUID 生成唯一文件名(保留原始擴(kuò)展名)
  • 按年月生成子目錄(防止單目錄文件過多)
  • 推薦存儲(chǔ)絕對(duì)路徑到數(shù)據(jù)庫(如:/images/202405/uuid123.jpg)

3、配置文件信息

# win環(huán)境文件存儲(chǔ)根目錄 
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 {
        // 驗(yàn)證文件類型
        if (!Arrays.asList("image", "video").contains(fileType)) {
            return ApiResult.error("Invalid file type");
        }
 
        // 生成存儲(chǔ)路徑
        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 {
        // 驗(yàn)證文件類型
        if (!Arrays.asList("image", "video").contains(fileType)) {
            return CommonResponse.buildErrorResponse("Error file type");
        }
        // 生成存儲(chǔ)路徑
        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);
        // 路徑安全校驗(yàn)
        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框架實(shí)現(xiàn)文件上傳下載分享功能的文章就介紹到這了,更多相關(guān)SpringBoot文件上傳下載分享內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

前郭尔| 祁门县| 澄迈县| 荣昌县| 连城县| 咸阳市| 亳州市| 广饶县| 宜丰县| 潞西市| 阳泉市| 泰宁县| 普安县| 留坝县| 家居| 启东市| 漳浦县| 晋中市| 浙江省| 牙克石市| 余姚市| 垣曲县| 洪雅县| 星子县| 南昌市| 沿河| 彭阳县| 府谷县| 噶尔县| 江北区| 郧西县| 瑞昌市| 永登县| 娄底市| 绥滨县| 巨鹿县| 安顺市| 海林市| 嘉禾县| 淮安市| 阳信县|