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

基于SpringBoot實(shí)現(xiàn)大文件分塊上傳功能

 更新時間:2024年09月06日 08:28:11   作者:HBLOG  
這篇文章主要介紹了基于SpringBoot實(shí)現(xiàn)大文件分塊上傳功能,實(shí)現(xiàn)原理其實(shí)很簡單,核心就是客戶端把大文件按照一定規(guī)則進(jìn)行拆分,比如20MB為一個小塊,分解成一個一個的文件塊,然后把這些文件塊單獨(dú)上傳到服務(wù)端,需要的朋友可以參考下

1.分塊上傳使用場景

  • 大文件加速上傳:當(dāng)文件大小超過100MB時,使用分片上傳可實(shí)現(xiàn)并行上傳多個Part以加快上傳速度。

  • 網(wǎng)絡(luò)環(huán)境較差:網(wǎng)絡(luò)環(huán)境較差時,建議使用分片上傳。當(dāng)出現(xiàn)上傳失敗的時候,您僅需重傳失敗的Part。

  • 文件大小不確定: 可以在需要上傳的文件大小還不確定的情況下開始上傳,這種場景在視頻 監(jiān)控等行業(yè)應(yīng)用中比較常見。

2.實(shí)現(xiàn)原理

實(shí)現(xiàn)原理其實(shí)很簡單,核心就是客戶端把大文件按照一定規(guī)則進(jìn)行拆分,比如20MB為一個小塊,分解成一個一個的文件塊,然后把這些文件塊單獨(dú)上傳到服務(wù)端,等到所有的文件塊都上傳完畢之后,客戶端再通知服務(wù)端進(jìn)行文件合并的操作,合并完成之后整個任務(wù)結(jié)束。

3.代碼工程

實(shí)驗(yàn)?zāi)康?/h3>

實(shí)現(xiàn)大文件分塊上傳

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>file</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-core</artifactId>
            <version>5.8.15</version>
        </dependency>
    </dependencies>
</project>

controller

package com.et.controller;

import com.et.bean.Chunk;
import com.et.bean.FileInfo;
import com.et.service.ChunkService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("file")
public class ChunkController {
    @Autowired
    private ChunkService chunkService;

    /**
     * upload by part
     *
     * @param chunk
     * @return
     */
    @PostMapping(value = "chunk")
    public ResponseEntity<String> chunk(Chunk chunk) {
        chunkService.chunk(chunk);
        return ResponseEntity.ok("File Chunk Upload Success");
    }

    /**
     * merge
     *
     * @param filename
     * @return
     */
    @GetMapping(value = "merge")
    public ResponseEntity<Void> merge(@RequestParam("filename") String filename) {
        chunkService.merge(filename);
        return ResponseEntity.ok().build();
    }


    /**
     * get fileName
     *
     * @return files
     */
    @GetMapping("/files")
    public ResponseEntity<List<FileInfo>> list() {
        return ResponseEntity.ok(chunkService.list());
    }

    /**
     * get single file
     *
     * @param filename
     * @return file
     */
    @GetMapping("/files/{filename:.+}")
    public ResponseEntity<Resource> getFile(@PathVariable("filename") String filename) {
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + filename + "\"").body(chunkService.getFile(filename));
    }
}

config

package com.et.config;

import com.et.service.FileClient;
import com.et.service.impl.LocalFileSystemClient;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;


@Configuration
public class FileClientConfig {
    @Value("${file.client.type:local-file}")
    private String fileClientType;

    private static final Map<String, Supplier<FileClient>> FILE_CLIENT_SUPPLY = new HashMap<String, Supplier<FileClient>>() {
        {
            put("local-file", LocalFileSystemClient::new);
           // put("aws-s3", AWSFileClient::new);
        }
    };

    /**
     * get client
     *
     * @return 
     */
    @Bean
    public FileClient fileClient() {
        return FILE_CLIENT_SUPPLY.get(fileClientType).get();
    }
}

service

package com.et.service;

import com.et.bean.Chunk;
import com.et.bean.FileInfo;

import org.springframework.core.io.Resource;

import java.util.List;


public interface ChunkService {

    void chunk(Chunk chunk);
    void merge(String filename);
    List<FileInfo> list();
    Resource getFile(String filename);
}

package com.et.service.impl;

import com.et.bean.Chunk;
import com.et.bean.ChunkProcess;
import com.et.bean.FileInfo;
import com.et.service.ChunkService;
import com.et.service.FileClient;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;


@Service
@Slf4j
public class ChunkServiceImpl implements ChunkService {
    // process
    private static final Map<String, ChunkProcess> CHUNK_PROCESS_STORAGE = new ConcurrentHashMap<>();

    // file list
    private static final List<FileInfo> FILE_STORAGE = new CopyOnWriteArrayList<>();

    @Autowired
    private FileClient fileClient;

    @Override
    public void chunk(Chunk chunk) {
        String filename = chunk.getFilename();
        boolean match = FILE_STORAGE.stream().anyMatch(fileInfo -> fileInfo.getFileName().equals(filename));
        if (match) {
            throw new RuntimeException("File [ " + filename + " ] already exist");
        }
        ChunkProcess chunkProcess;
        String uploadId;
        if (CHUNK_PROCESS_STORAGE.containsKey(filename)) {
            chunkProcess = CHUNK_PROCESS_STORAGE.get(filename);
            uploadId = chunkProcess.getUploadId();
            AtomicBoolean isUploaded = new AtomicBoolean(false);
            Optional.ofNullable(chunkProcess.getChunkList()).ifPresent(chunkPartList ->
                    isUploaded.set(chunkPartList.stream().anyMatch(chunkPart -> chunkPart.getChunkNumber() == chunk.getChunkNumber())));
            if (isUploaded.get()) {
                log.info("file【{}】chunk【{}】upload,jump", chunk.getFilename(), chunk.getChunkNumber());
                return;
            }
        } else {
            uploadId = fileClient.initTask(filename);
            chunkProcess = new ChunkProcess().setFilename(filename).setUploadId(uploadId);
            CHUNK_PROCESS_STORAGE.put(filename, chunkProcess);
        }

        List<ChunkProcess.ChunkPart> chunkList = chunkProcess.getChunkList();
        String chunkId = fileClient.chunk(chunk, uploadId);
        chunkList.add(new ChunkProcess.ChunkPart(chunkId, chunk.getChunkNumber()));
        CHUNK_PROCESS_STORAGE.put(filename, chunkProcess.setChunkList(chunkList));
    }

    @Override
    public void merge(String filename) {
        ChunkProcess chunkProcess = CHUNK_PROCESS_STORAGE.get(filename);
        fileClient.merge(chunkProcess);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = simpleDateFormat.format(new Date());
        FILE_STORAGE.add(new FileInfo().setUploadTime(currentTime).setFileName(filename));
        CHUNK_PROCESS_STORAGE.remove(filename);
    }

    @Override
    public List<FileInfo> list() {
        return FILE_STORAGE;
    }

    @Override
    public Resource getFile(String filename) {
        return fileClient.getFile(filename);
    }
}

package com.et.service.impl;

import com.et.bean.FileInfo;
import com.et.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;


@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {
    @Value("${upload.path:/data/upload/}")
    private String filePath;

    private static final List<FileInfo> FILE_STORAGE = new CopyOnWriteArrayList<>();

    @Override
    public void upload(MultipartFile[] files) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            boolean match = FILE_STORAGE.stream().anyMatch(fileInfo -> fileInfo.getFileName().equals(fileName));
            if (match) {
                throw new RuntimeException("File [ " + fileName + " ] already exist");
            }

            String currentTime = simpleDateFormat.format(new Date());
            try (InputStream in = file.getInputStream();
                 OutputStream out = Files.newOutputStream(Paths.get(filePath + fileName))) {
                FileCopyUtils.copy(in, out);
            } catch (IOException e) {
                log.error("File [{}] upload failed", fileName, e);
                throw new RuntimeException(e);
            }
            FileInfo fileInfo = new FileInfo().setFileName(fileName).setUploadTime(currentTime);
            FILE_STORAGE.add(fileInfo);
        }
    }

    @Override
    public List<FileInfo> list() {
        return FILE_STORAGE;
    }

    @Override
    public Resource getFile(String fileName) {
        FILE_STORAGE.stream()
                .filter(info -> info.getFileName().equals(fileName))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("File [ " + fileName + " ] not exist"));
        File file = new File(filePath + fileName);
        return new FileSystemResource(file);
    }
}

以上只是一些關(guān)鍵代碼,所有代碼請參見下面代碼倉庫

代碼倉庫

4.測試

  • 啟動Sprint Boot應(yīng)用

  • 編寫測試類

@Test
public void testUpload() throws Exception {
    String chunkFileFolder = "D:/tmp/";
    java.io.File file = new java.io.File("D:/SoftWare/oss-browser-win32-ia32.zip");
    long contentLength = file.length();
    // partSize:20MB
    long partSize = 20 * 1024 * 1024;
    // the last partSize may less  20MB
    long chunkFileNum = (long) Math.ceil(contentLength * 1.0 / partSize);
    RestTemplate restTemplate = new RestTemplate();

    try (RandomAccessFile raf_read = new RandomAccessFile(file, "r")) {
        // buffer
        byte[] b = new byte[1024];
        for (int i = 1; i <= chunkFileNum; i++) {
            // chunk
            java.io.File chunkFile = new java.io.File(chunkFileFolder + i);
            // write
            try (RandomAccessFile raf_write = new RandomAccessFile(chunkFile, "rw")) {
                int len;
                while ((len = raf_read.read(b)) != -1) {
                    raf_write.write(b, 0, len);
                    if (chunkFile.length() >= partSize) {
                        break;
                    }
                }
                // upload
                MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
                body.add("file", new FileSystemResource(chunkFile));
                body.add("chunkNumber", i);
                body.add("chunkSize", partSize);
                body.add("currentChunkSize", chunkFile.length());
                body.add("totalSize", contentLength);
                body.add("filename", file.getName());
                body.add("totalChunks", chunkFileNum);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);
                HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
                String serverUrl = "http://localhost:8080/file/chunk";
                ResponseEntity<String> response = restTemplate.postForEntity(serverUrl, requestEntity, String.class);
                System.out.println("Response code: " + response.getStatusCode() + " Response body: " + response.getBody());
            } finally {
                FileUtil.del(chunkFile);
            }
        }
    }
    // merge file
    String mergeUrl = "http://localhost:8080/file/merge?filename=" + file.getName();
    ResponseEntity<String> response = restTemplate.getForEntity(mergeUrl, String.class);
    System.out.println("Response code: " + response.getStatusCode() + " Response body: " + response.getBody());
}
  • 運(yùn)行測試類,日志如下

以上就是基于SpringBoot實(shí)現(xiàn)大文件分塊上傳功能的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot大文件分塊上傳的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • java根據(jù)List內(nèi)對象的屬性排序方法

    java根據(jù)List內(nèi)對象的屬性排序方法

    下面小編就為大家分享一篇java根據(jù)List內(nèi)對象的屬性排序方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-01-01
  • Java基礎(chǔ)之?dāng)?shù)組超詳細(xì)知識總結(jié)

    Java基礎(chǔ)之?dāng)?shù)組超詳細(xì)知識總結(jié)

    這篇文章主要介紹了Java基礎(chǔ)之?dāng)?shù)組詳解,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java基礎(chǔ)的小伙伴們有很好的幫助,需要的朋友可以參考下
    2021-05-05
  • Java基于UDP協(xié)議實(shí)現(xiàn)簡單的聊天室程序

    Java基于UDP協(xié)議實(shí)現(xiàn)簡單的聊天室程序

    這篇文章主要為大家詳細(xì)介紹了Java基于UDP協(xié)議實(shí)現(xiàn)簡單的聊天室程序的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-07-07
  • 詳解Springboot 優(yōu)雅停止服務(wù)的幾種方法

    詳解Springboot 優(yōu)雅停止服務(wù)的幾種方法

    這篇文章主要介紹了詳解Springboot 優(yōu)雅停止服務(wù)的幾種方法 ,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • java加密MD5實(shí)現(xiàn)及密碼驗(yàn)證代碼實(shí)例

    java加密MD5實(shí)現(xiàn)及密碼驗(yàn)證代碼實(shí)例

    這篇文章主要介紹了java加密MD5實(shí)現(xiàn)及密碼驗(yàn)證代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-12-12
  • 使用SpringBoot創(chuàng)建一個RESTful API的詳細(xì)步驟

    使用SpringBoot創(chuàng)建一個RESTful API的詳細(xì)步驟

    使用 Java 的 Spring Boot 創(chuàng)建 RESTful API 可以滿足多種開發(fā)場景,它提供了快速開發(fā)、易于配置、可擴(kuò)展、可維護(hù)的優(yōu)點(diǎn),尤其適合現(xiàn)代軟件開發(fā)的需求,幫助你快速構(gòu)建出高性能的后端服務(wù),需要的朋友可以參考下
    2025-01-01
  • Java深入理解代碼塊的使用細(xì)節(jié)

    Java深入理解代碼塊的使用細(xì)節(jié)

    所謂代碼塊是指用"{}"括起來的一段代碼,根據(jù)其位置和聲明的不同,可以分為普通代碼塊、構(gòu)造塊、靜態(tài)塊、和同步代碼塊。如果在代碼塊前加上?synchronized關(guān)鍵字,則此代碼塊就成為同步代碼塊
    2022-05-05
  • Java手寫Redis服務(wù)端的實(shí)現(xiàn)

    Java手寫Redis服務(wù)端的實(shí)現(xiàn)

    本文主要介紹了Java手寫Redis服務(wù)端的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-12-12
  • MyEclipse如何將項(xiàng)目的開發(fā)環(huán)境與服務(wù)器的JDK 版本保持一致

    MyEclipse如何將項(xiàng)目的開發(fā)環(huán)境與服務(wù)器的JDK 版本保持一致

    我們使用MyEclipse開發(fā)Java項(xiàng)目開發(fā)中,偶爾會遇到因項(xiàng)目開發(fā)環(huán)境不協(xié)調(diào),導(dǎo)致這樣那樣的問題,在這里以把所有環(huán)境調(diào)整為JDK1.6 為例,給大家詳細(xì)介紹MyEclipse如何將項(xiàng)目的開發(fā)環(huán)境與服務(wù)器的JDK 版本保持一致,需要的朋友參考下吧
    2024-04-04
  • Springboot WebFlux集成Spring Security實(shí)現(xiàn)JWT認(rèn)證的示例

    Springboot WebFlux集成Spring Security實(shí)現(xiàn)JWT認(rèn)證的示例

    這篇文章主要介紹了Springboot WebFlux集成Spring Security實(shí)現(xiàn)JWT認(rèn)證的示例,幫助大家更好的理解和學(xué)習(xí)使用springboot框架,感興趣的朋友可以了解下
    2021-04-04

最新評論

响水县| 长白| 沿河| 平陆县| 林芝县| 桃江县| 池州市| 武宣县| 石泉县| 富民县| 康定县| 德安县| 湘阴县| 剑河县| 永福县| 星座| 佛教| 千阳县| 广河县| 广元市| 泰州市| 卓尼县| 乌兰察布市| 林周县| 青州市| 荃湾区| 齐河县| 墨脱县| 杭锦后旗| 通道| 浦东新区| 都江堰市| 锦州市| 莱西市| 石阡县| 郁南县| 乌拉特后旗| 天全县| 台湾省| 三台县| 剑阁县|