java實現文件切片上傳百度雲+斷點續傳的方法

前言:

本文代碼通過dubbo進行遠程調用的接口,如果不使用dubbo,直接將service放到你的service,並稍作修改,redis替換成自己封裝的工具即可。下方代碼有點多,但基本上都加註釋瞭。

切片上傳百度雲和上傳到本地有所不同,上傳到本地是需要前端給個唯一標識,通過自定義唯一標識保存到本地,最後在合並文件。而上傳百度雲則需要直接把切片傳到百度雲,唯一標識uploadId是百度雲提供的,上傳及合並都是直接調用百度雲提供的接口。下方為百度雲的使用文檔。

對象存儲BOS – 文件管理 | 百度智能雲文檔 (baidu.com)

1.定義一個實體類

用於接收前臺傳過來的信息,信息應該包括總切片數,當前切片數,文件名稱,文件總大小。

import com.geely.tcm.common.annotation.Excel;
import lombok.Data;
 
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
 
 
@Data
public class MutilFileInfo implements Serializable {
    private static final long serialVersionUID = 1L;
 
    @NotNull(message = "車型不能為空")
    @Excel(name = "車型")
    private String model;
 
    @Excel(name = "文件名稱")
    private String name;
 
    @Excel(name = "文件總大小")
    private Long totalSize;
 
    @Min(value = 1, message = "不能小於1")
    @Max(value = 10000, message = "不能大於10000")
    @Excel(name = "當前分片序號")
    private Integer chunk;
 
    @Min(value = 1, message = "不能小於1")
    @Max(value = 10000, message = "不能大於10000")
    @Excel(name = "分片總數")
    private Integer chunks;
}

2.創建controller

用於處理前端過來的文件及信息

import com.alibaba.fastjson.JSON;
import com.baidubce.services.bos.model.PartETag;
import com.geely.tcm.common.annotation.Log;
import com.geely.tcm.common.bean.MutilFileInfo;
import com.geely.tcm.common.bean.baidu.CustomPartETag;
import com.geely.tcm.common.bean.measure.Cmm3dModel;
import com.geely.tcm.common.configuration.RedisUtils;
import com.geely.tcm.common.enums.BusinessType;
import com.geely.tcm.common.util.StringUtils;
import com.geely.tcom.remote.api.baidu.BaiduCloudBosService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
 
import java.util.*;
import java.util.concurrent.Semaphore;
import java.util.stream.Collectors;
 
@Api(tags = "文件上傳下載服務")
@RequestMapping("/threeModel")
@RestController
@Slf4j
public class Model3DController1  {
    //DubboReference這個是遠程調用,如果沒有遠程調用,直接Autowired就可以
    @DubboReference(version = "${sheet.service.version}")
    private BaiduCloudBosService baiduCloudBosService;
    //通過加鎖保證線程安全
    private Semaphore lock = new Semaphore(1);
 
    //api開頭的這些是swagger用到的,如果沒使用swagger可以刪到PostMapping上邊
    @ApiOperation(value = "obj模型上傳")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "totalSize", value = "文件總大小",dataTypeClass = Long.class),
            @ApiImplicitParam(name = "chunks", value = "總切片數",dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "chunk", value = "當前切片數",dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "model", value = "車型",dataTypeClass = String.class),
            @ApiImplicitParam(name = "file", value = "切片文件",dataTypeClass = MultipartFile.class)
    })
    @Log(title = "obj模型上傳", businessType = BusinessType.INSERT)
    @PostMapping("/upload3DToBos")
    public Object upload3DToBos( MutilFileInfo fileinfo, @RequestParam(required=false,value="file") MultipartFile multipartFile) {
        String model=fileinfo.getModel().trim();
        Map<String,Object> m=new HashMap();
        String fileName=fileinfo.getName();
        if (StringUtils.isEmpty(fileName)) {//判斷文件名稱是否為空
            m.put("key","error");
            m.put("value","文件名不能為空");
            return m;
        }
        if (multipartFile == null) {//判斷上傳過來的切片是否為空
            m.put("key","error");
            m.put("value","請上傳文件");
            return m;
        }
        try{
            String filePath="/test/"+model+"/"+fileName;//拼接百度雲地址
            String redisKey="partETags-"+model+"-"+fileName;//緩存的鍵
            Integer current =fileinfo.getChunk();//當前切片數
            Integer total = fileinfo.getChunks();//總切片數
            Long size=multipartFile.getSize();//文件大小
            String uploadId = getUploadId(redisKey, filePath);//該方法獲取百度雲的唯一標識uploadId
            byte[] file = multipartFile.getBytes();//將切片過來的文件轉成字節數組
            if(current==1){//這塊進行斷點續傳,如果是第一個切片,查詢一下緩存中是否有數據瞭,如果有返回給前臺,如果沒有進行上傳
                if(getCurrentEqualsOne(redisKey).size()>0) {
                    //給前臺提供是否緩存中已有數據
                    return getCurrentEqualsOne(redisKey);
                }
            }
            //切片上傳百度雲
            List<CustomPartETag> customPartETags = getPartEtags(redisKey, uploadId, filePath, file, size, current);
            //如果緩存中成功的切片數等於總數,那麼進行合並
            if (customPartETags.size() == total) {
                customPartETags = customPartETags.stream().sorted(Comparator.comparing(PartETag::getPartNumber)).collect(Collectors.toList());//進行排序
                baiduCloudBosService.completePart(uploadId, customPartETags, filePath);//執行合並
                RedisUtils.hdel(redisKey,"uploadId","customPartETags");//如果合並成功,刪除緩存中的數據
                // 入庫做記錄
                m.put("key","success");
                m.put("value","上傳成功");
                return m;
            }
            m.put("key","continue");
            m.put("value",current+1);
            return m;
        }catch (Exception e){
            e.printStackTrace();
            m.put("key","error");
            m.put("value","上傳失敗");
            return m;
        }
    }
 
    /**
     * 獲取 part
     *
     * @param redisPartKey redisKey
     * @return
     */
    private List<CustomPartETag> getPartEtags(String redisPartKey, String uploadId, String filePath,  byte[] file, long size, int current) {
        List<CustomPartETag> customPartETags = null;
        try {
            lock.acquire();
            //因為每次上傳成功後都會把成功的切片存進百度雲,如註解下方第四行代碼,所以每次上傳之前需要先取出來,將成功的切片放進去
            customPartETags = RedisUtils.hget(redisPartKey, "customPartETags") == null ? new ArrayList<>() : JSON.parseArray((String) RedisUtils.hget(redisPartKey, "customPartETags"), CustomPartETag.class);
            //上傳百度雲成功之後會返回一個PartETagg對象,由於項目中存在dubbo,顧將CustomPartETag類繼承PartETagg進行序列化
            CustomPartETag customPartETag = baiduCloudBosService.uploadCustomPartETag(uploadId, filePath, file, size, current);
            customPartETags.add(customPartETag);
            setPartEtagsToRedis(redisPartKey, customPartETags);
 
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.release();
        }
        return customPartETags;
    }
 
    /**
     * 獲取 uploadId
     *
     * @param redisPartKey redisKey
     * @param filePath     filePath
     * @return
     */
    private String getUploadId(String redisPartKey, String filePath) {
        String uploadId = null;
        try {
            lock.acquire();//線程鎖
            uploadId = (String) RedisUtils.hget(redisPartKey, "uploadId");//先去redis中找,是否已經有uploadId
            if (StringUtils.isEmpty(uploadId)) {//判斷是否為空,如果為空,說明之前沒上傳過,為首次上傳,如果已經存在,返回該uploadId
                uploadId = baiduCloudBosService.initMultipartUpload(filePath);//進行初始化,返回一個唯一標識uploadId
                RedisUtils.hset(redisPartKey, "uploadId", uploadId, 60 * 60);//將返回來的uploadId放到緩存中,下個切片上傳直接使用這個uploadId
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.release();
        }
        return uploadId;
    }
 
    /**
     * 薄墩 partKey到redis
     *
     * @param redisPartKey
     * @param customPartETags
     */
    private void setPartEtagsToRedis(String redisPartKey, List<CustomPartETag> customPartETags) {
        RedisUtils.hset(redisPartKey, "customPartETags", JSON.toJSONString(customPartETags), 60 * 60);
    }
    public Map<String,Object> getCurrentEqualsOne(String redisKey){
        Map<String,Object> m=new HashMap<>();
        List<CustomPartETag>  customPartETags = RedisUtils.hget(redisKey, "customPartETags") == null ? new ArrayList<>() : JSON.parseArray((String) RedisUtils.hget(redisKey, "customPartETags"), CustomPartETag.class);
        //給前臺提供是否緩存中已有數據
        if(customPartETags.size()==0){
            return m;
        }else{
                //緩存中有數據,返回緩存中數據
                int t=  customPartETags.get(customPartETags.size()-1).getPartNumber();
                m.put("key","hasValue");
                m.put("value",t);
                return  m;
            }
    }
}

3.遠程的service

(如果不用遠程調用,直接創建一個service就可以)

package com.geely.tcm.sheet.service;
 
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.model.*;
import com.geely.tcm.common.bean.baidu.BosResult;
import com.geely.tcm.common.bean.baidu.CustomPartETag;
import com.geely.tcm.common.util.StringUtils;
import com.geely.tcom.remote.api.baidu.BaiduCloudBosService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
 
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
 
/**
 * 百度私有雲服務操作
 *
 * @author : wangbin
 * @date : 2021/9/24
 * @since : 1.0.0
 */
@Slf4j
@DubboService(version = "${sheet.service.version}")
public class BaiduCloudBosServiceImpl{
 
    @Autowired
    private BosClient bosClient;
 
   
    public String initMultipartUpload(String filePath) {
        // 開始Multipart Upload
        InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(null, filePath);
        InitiateMultipartUploadResponse initiateMultipartUploadResponse = bosClient.initiateMultipartUpload(initiateMultipartUploadRequest);
        // 打印UploadId,它是區分分塊上傳事件的唯一標識
        String uploadId = initiateMultipartUploadResponse.getUploadId();
        log.info("filePath= {},uploadId = {}", filePath, uploadId);
        return uploadId;
    }
 
 
    public CustomPartETag uploadCustomPartETag(String uploadId, String filePath, byte[] file, long partSize, int partNumber) {
        UploadPartRequest uploadPartRequest = new UploadPartRequest();
        uploadPartRequest.setBucketName(null);
        uploadPartRequest.setKey(filePath);
        uploadPartRequest.setUploadId(uploadId);
        InputStream input= new ByteArrayInputStream(file);
        uploadPartRequest.setInputStream(input);
        uploadPartRequest.setPartSize(partSize);
        uploadPartRequest.setPartNumber(partNumber );
        uploadPartRequest.setMd5Digest("");
        UploadPartResponse uploadPartResponse = bosClient.uploadPart(uploadPartRequest);
        PartETag partETag = uploadPartResponse.getPartETag();
        CustomPartETag  customPartETag = new CustomPartETag();
        customPartETag.setETag(partETag.getETag());
        customPartETag.setPartNumber(partETag.getPartNumber());
        return customPartETag;
    }
 
    /**
     * 分塊上傳結束之後,當所有的數據Part驗證通過後,BOS將把這些數據part組合成一個完整的Object
     *
     * @param uploadId
     * @param customPartETags
     * @param filePath
     */
    public void completePart(String uploadId, List<CustomPartETag> customPartETags, String filePath) {
        //for循環轉一下 CustomPartETag 轉PartETag
        if(customPartETags.size()>0){
            List<PartETag> partETags=new ArrayList<>();
            for(CustomPartETag c:customPartETags){
                PartETag partETag=new PartETag();
                partETag.setETag(c.getETag());
                partETag.setPartNumber(c.getPartNumber());
                partETags.add(partETag);
            }
            CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(null, filePath, uploadId, partETags);
            CompleteMultipartUploadResponse completeMultipartUploadResponse = bosClient.completeMultipartUpload(completeMultipartUploadRequest);
            log.info("完成分片上傳 , filePath = {},uploadId = {}, etag = {}", filePath, uploadId,completeMultipartUploadResponse.getETag());
        }
    }
}

4.定義一個實體類

繼承,實現序列化,(dubbo不序列化就會傳不過去)

import com.baidubce.services.bos.model.PartETag;
import java.io.Serializable;
 
public class CustomPartETag extends PartETag implements Serializable {
}

5.這裡提供一個臨時測試的前端代碼

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>upload</title>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
    <input type="file" name="file" id="file">
    <button id="upload" onClick="upload()">upload</button>
    <script type="text/javascript">
        var bytesPerPiece = 1024 * 1024; // 每個文件切片大小定為1MB .
        var totalPieces;
        
        function upload() {
            var blob = document.getElementById("file").files[0];
            var start = 0;
            var end;
            var index = 1;
            var filesize = blob.size;
            var filename = blob.name;
 
            //計算文件切片總數
            totalPieces = Math.ceil(filesize / bytesPerPiece);
            while(start < filesize) {
                end = start + bytesPerPiece;
                if(end > filesize) {
                    end = filesize;
                }
 
                var chunk = blob.slice(start,end);//切割文件    
                var sliceIndex= blob.name + index;
                var formData = new FormData();
                formData.append("file", chunk, filename);
    formData.append("totalSize",filesize);
    formData.append("chunks",totalPieces);
    formData.append("chunk",index);
    formData.append("model",'kx11');
                $.ajax({
//路徑換成你的路徑
                    url: 'http://127.0.0.1:6300/threeModel/upload3DToBos',
                    type: 'POST',
     dataType:'json',
                    cache: false,
                    data: formData,
                    processData: false,
                    contentType: false,
     mimeType: "multipart/form-data",
     success: function (result){
      console.log(result.value);
     }
    });
    
    
                start = end;
                index++;
            }
        }
    </script>
</body>
</html>

到此這篇關於java實現文件切片上傳百度雲+斷點續傳的方法的文章就介紹到這瞭,更多相關java 文件切片上傳 內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: