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

基于SpringBoot實(shí)現(xiàn)文件秒傳功能

 更新時(shí)間:2025年04月01日 09:10:35   作者:風(fēng)象南  
在開發(fā)Web應(yīng)用時(shí),文件上傳是一個(gè)常見需求,然而,當(dāng)用戶需要上傳大文件或相同文件多次時(shí),會造成帶寬浪費(fèi)和服務(wù)器存儲冗余,此時(shí)可以使用文件秒傳技術(shù)通過識別重復(fù)文件,本文就給大家介紹了如何基于SpringBoot實(shí)現(xiàn)文件秒傳功能,需要的朋友可以參考下

前言

在開發(fā)Web應(yīng)用時(shí),文件上傳是一個(gè)常見需求。然而,當(dāng)用戶需要上傳大文件或相同文件多次時(shí),會造成帶寬浪費(fèi)和服務(wù)器存儲冗余。此時(shí)可以使用文件秒傳技術(shù)通過識別重復(fù)文件,實(shí)現(xiàn)瞬間完成上傳的效果,大大提升了用戶體驗(yàn)和系統(tǒng)效率。

文件秒傳原理

文件秒傳的核心原理是:

  • 計(jì)算文件唯一標(biāo)識(通常是MD5或SHA256值)
  • 上傳前先檢查服務(wù)器是否已存在相同標(biāo)識的文件
  • 若存在,則直接引用已有文件,無需再次上傳
  • 若不存在,則執(zhí)行常規(guī)上傳流程

這種方式能顯著減少網(wǎng)絡(luò)傳輸避免存儲冗余。

代碼實(shí)現(xiàn)

1. 創(chuàng)建項(xiàng)目基礎(chǔ)結(jié)構(gòu)

首先創(chuàng)建Spring Boot項(xiàng)目,添加必要依賴:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.7.18</version>
    </dependency>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.8.1</version>
    </dependency>
</dependencies>

2. 創(chuàng)建上傳存儲代碼

此處使用一個(gè)簡單的集合來存儲文件信息,實(shí)際使用需要替換為數(shù)據(jù)庫或其他持久化中間件。

import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class FileService {
    
    // 使用Map存儲文件信息,key為MD5,value為文件信息(實(shí)際使用時(shí)可替換為數(shù)據(jù)庫存儲)
    private final Map<String, FileInfo> fileStore = new ConcurrentHashMap<>();
    
    /**
     * 檢查文件是否已存在
     */
    public FileInfo findByMd5(String md5) {
        return fileStore.get(md5);
    }
    
    /**
     * 保存文件信息
     */
    public FileInfo saveFile(String fileName, String fileMd5, Long fileSize, String filePath) {
        FileInfo fileInfo = new FileInfo(fileName, fileMd5, fileSize, filePath);
        fileStore.put(fileMd5, fileInfo); // 實(shí)際使用時(shí)插入數(shù)據(jù)庫
        return fileInfo;
    }
    
    /**
     * 計(jì)算文件MD5
     */
    public String calculateMD5(MultipartFile file) throws IOException {
        return DigestUtil.md5Hex(file.getInputStream());
    }
}

定義一個(gè)簡單的文件信息實(shí)體類:

import cn.hutool.core.util.IdUtil;

public class FileInfo {

    private String id = IdUtil.fastUUID();
    private String fileName;
    private String fileMd5;
    private Long fileSize;
    private String filePath;

    public FileInfo(String fileName, String fileMd5, Long fileSize, String filePath) {
        this.fileName = fileName;
        this.fileMd5 = fileMd5;
        this.fileSize = fileSize;
        this.filePath = filePath;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileMd5() {
        return fileMd5;
    }

    public void setFileMd5(String fileMd5) {
        this.fileMd5 = fileMd5;
    }

    public Long getFileSize() {
        return fileSize;
    }

    public void setFileSize(Long fileSize) {
        this.fileSize = fileSize;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
}

3. 創(chuàng)建Result類

為了統(tǒng)一返回結(jié)果格式,可以創(chuàng)建一個(gè)簡單的Result類。

public class Result {
    private boolean success;
    private Object data;
    private String message;

    public Result(boolean success, Object data, String message) {
        this.success = success;
        this.data = data;
        this.message = message;
    }

    public static Result success(Object data) {
        return new Result(true, data,"success");
    }

    public static Result success(Object data,String message) {
        return new Result(true, data,message);
    }

    public static Result error(String message) {
        return new Result(false, null, message);
    }

    // Getters
    public boolean isSuccess() { return success; }
    public Object getData() { return data; }
    public String getMessage() { return message; }
}

4. 創(chuàng)建Controller控制器

import cn.hutool.core.io.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RestController
@RequestMapping("/api/file")
public class FileController {

    private static Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService fileService;

    /**
     * 檢查文件是否已存在
     */
    @PostMapping("/check")
    public Result checkFile(@RequestParam("md5") String md5) {
        FileInfo fileInfo = fileService.findByMd5(md5);
        if (fileInfo != null) {
            return Result.success(fileInfo);
        }
        return Result.success(null);
    }
    
    /**
     * 上傳文件
     */
    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 計(jì)算文件MD5值
            String md5 = fileService.calculateMD5(file);
            
            // 檢查文件是否已存在
            FileInfo existFile = fileService.findByMd5(md5);
            if (existFile != null) {
                // todo 進(jìn)行自定義的邏輯處理
                return Result.success(existFile,"文件秒傳成功");
            }
            
            // 文件不存在,執(zhí)行上傳
            String originalFilename = file.getOriginalFilename();
            String filePath = FileUtil.getTmpDir() + File.separator + originalFilename; // 保存到臨時(shí)目錄
            
            // 存儲文件
            file.transferTo(new File(filePath));
            
            // 保存文件信息到內(nèi)存(實(shí)際使用時(shí)應(yīng)替換為數(shù)據(jù)庫)
            FileInfo fileInfo = fileService.saveFile(originalFilename, md5, file.getSize(), filePath);
            return Result.success(fileInfo,"文件上傳成功");
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return Result.error("文件上傳失?。? + e.getMessage());
        }
    }
}

4. 創(chuàng)建純HTML前端頁面

創(chuàng)建一個(gè)簡單的HTML上傳頁面:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>文件秒傳示例</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/spark-md5@3.0.2/spark-md5.min.js"></script>
</head>
<body>
    <h2>文件上傳(支持秒傳)</h2>
    <input type="file" id="fileInput" />
    <button onclick="uploadFile()">上傳文件</button>
    <div id="progressBar" style="display:none;">
        <div>上傳進(jìn)度:<span id="progress">0%</span></div>
    </div>
    <div id="result"></div>
    <script>
        function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            if (!file) {
                alert('請選擇文件');
                return;
            }
            
            document.getElementById('progressBar').style.display = 'block';
            document.getElementById('result').innerText = '計(jì)算文件MD5中...';

            // 計(jì)算文件MD5
            calculateMD5(file).then(md5 => {
                document.getElementById('result').innerText = '正在檢查文件是否已存在...';
                
                // 檢查文件是否已存在
                return axios.post('/api/file/check', {
                    md5: md5
                }).then(response => {
                    if (response.data.data && response.data.data.id) {
                        // 文件已存在,執(zhí)行秒傳
                        document.getElementById('result').innerText = '文件秒傳成功!';
                        document.getElementById('progress').innerText = '100%';
                        return Promise.resolve();
                    } else {
                        // 文件不存在,執(zhí)行上傳
                        const formData = new FormData();
                        formData.append('file', file);
                        
                        return axios.post('/api/file/upload', formData, {
                            onUploadProgress: progressEvent => {
                                const percentCompleted = Math.round(
                                    (progressEvent.loaded * 100) / progressEvent.total
                                );
                                document.getElementById('progress').innerText = percentCompleted + '%';
                            }
                        }).then(response => {
                            document.getElementById('result').innerText = '文件上傳成功!';
                        });
                    }
                });
            }).catch(error => {
                document.getElementById('result').innerText = '錯(cuò)誤:' + error.message;
            });
        }
        
        // 計(jì)算文件MD5
        function calculateMD5(file) {
            return new Promise((resolve, reject) => {
                const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
                const chunkSize = 2097152; // 2MB
                const chunks = Math.ceil(file.size / chunkSize);
                let currentChunk = 0;
                const spark = new SparkMD5.ArrayBuffer();
                const fileReader = new FileReader();
                
                fileReader.onload = function(e) {
                    spark.append(e.target.result);
                    currentChunk++;
                    
                    if (currentChunk < chunks) {
                        loadNext();
                    } else {
                        resolve(spark.end());
                    }
                };
                
                fileReader.onerror = function() {
                    reject('文件讀取錯(cuò)誤');
                };
                
                function loadNext() {
                    const start = currentChunk * chunkSize;
                    const end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
                    fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
                }
                
                loadNext();
            });
        }
    </script>
</body>
</html>

5. 配置文件

application.yml中添加必要配置

server:
  port: 8080

spring:
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB

效果

第一次上傳

第二次上傳

到此這篇關(guān)于基于SpringBoot實(shí)現(xiàn)文件秒傳功能的文章就介紹到這了,更多相關(guān)SpringBoot文件秒傳內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • IntelliJ IDEA配置Tomcat(完整版圖文教程)

    IntelliJ IDEA配置Tomcat(完整版圖文教程)

    這篇文章主要介紹了IntelliJ IDEA配置Tomcat(完整版圖文教程),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-05-05
  • java foreach循環(huán)為什么不能賦值的講解

    java foreach循環(huán)為什么不能賦值的講解

    這篇文章主要介紹了java foreach循環(huán)為什么不能賦值的講解,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • 基于JVM 中常見垃圾收集算法介紹

    基于JVM 中常見垃圾收集算法介紹

    下面小編就為大家分享一篇基于JVM 中常見垃圾收集算法介紹,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-01-01
  • 23種設(shè)計(jì)模式(20)java中介者模式

    23種設(shè)計(jì)模式(20)java中介者模式

    這篇文章主要為大家詳細(xì)介紹了23種設(shè)計(jì)模式之java中介者模式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • Java自定義數(shù)組列表的實(shí)現(xiàn)操作

    Java自定義數(shù)組列表的實(shí)現(xiàn)操作

    這篇文章主要介紹了Java自定義數(shù)組列表的實(shí)現(xiàn)操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • JVM工作原理和工作流程簡述

    JVM工作原理和工作流程簡述

    這篇文章主要介紹了關(guān)于JVM工作原理簡述,主要弄清楚jvm運(yùn)行的來龍去脈,感興趣的可以一起來了解一下
    2020-07-07
  • SpringBoot啟用GZIP壓縮的代碼工程

    SpringBoot啟用GZIP壓縮的代碼工程

    經(jīng)常我們都會與服務(wù)端進(jìn)行大數(shù)據(jù)量的文本傳輸,例如?JSON?就是常見的一種格式,通過?REST?API?接口進(jìn)行?GET?和?POST?請求,可能會有大量的文本格式數(shù)據(jù)提交、返回,壓縮和解壓在提升網(wǎng)絡(luò)帶寬的同時(shí),會帶來?CPU?資源的損耗,本文介紹了SpringBoot啟用GZIP壓縮的代碼工程
    2024-08-08
  • idea2020.3測試評價(jià)及感受

    idea2020.3測試評價(jià)及感受

    idea2020.3版本這次變化最大的也就是 UI了完全拋棄了之前一直使用的模板更改成了新的樣式,感興趣的朋友快來下載體驗(yàn)下吧
    2020-10-10
  • 一文帶你學(xué)會Java網(wǎng)絡(luò)編程

    一文帶你學(xué)會Java網(wǎng)絡(luò)編程

    網(wǎng)絡(luò)編程是指編寫運(yùn)行在多個(gè)設(shè)備(計(jì)算機(jī))的程序,這些設(shè)備都通過網(wǎng)絡(luò)連接起來。這篇文章將帶大家深入了解一下Java的網(wǎng)絡(luò)編程,需要的可以了解一下
    2022-08-08
  • Java Bean的作用域,生命周期和注解

    Java Bean的作用域,生命周期和注解

    這篇文章主要介紹了淺談Spring中Bean的作用域,生命周期和注解,具有一定借鑒價(jià)值,需要的朋友可以參考下,希望能夠給你帶來幫助
    2021-11-11

最新評論

蒲江县| 万荣县| 沂水县| 绵阳市| 略阳县| 四子王旗| 莆田市| 上林县| 揭阳市| 攀枝花市| 靖州| 手机| 永福县| 奉贤区| 秦皇岛市| 沧源| 珠海市| 宣城市| 额尔古纳市| 广南县| 兴国县| 梨树县| 蓬安县| 遂昌县| 丰原市| 南阳市| 黄骅市| 大方县| 浙江省| 新和县| 大丰市| 和平区| 休宁县| 康定县| 房产| 汝南县| 阿克苏市| 江口县| 黔南| 东光县| 依兰县|