實(shí)現(xiàn)前后端視頻文件的斷點(diǎn)續(xù)傳功能

實(shí)現(xiàn)IO流拆分合并的集合功能(多個(gè)文本文件進(jìn)行合并/一個(gè)視頻文件切割成單個(gè)文件/多個(gè)視頻流合并成單個(gè)視頻文件/前后端視頻文件的斷點(diǎn)續(xù)傳功能)

package com.example.yygoods.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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.io.*;

@RestController
public class SequenceStream {
    Vector<InputStream> vectorStreams = new Vector<>();
    /*
     * 實(shí)現(xiàn)多個(gè)文本文件進(jìn)行合并
     * Vector作用和數(shù)組類似,存儲數(shù)據(jù),功能會比數(shù)組強(qiáng)大,如: 可以返回枚舉類型數(shù)據(jù)
     * 注釋:SequenceInputStream參數(shù)必須是枚舉類型的數(shù)據(jù)
     * vectorStreams.elements()返回此向量的組件的枚舉
     **/
    @GetMapping("/streamMerge")
    public String streamMerge () {
        try {
            String UPLOAD_DIR = System.getProperty("user.dir");
            InputStream inputStream_a = new FileInputStream(UPLOAD_DIR + "\\1.txt");
            InputStream inputStream_b = new FileInputStream(UPLOAD_DIR + "\\2.txt");
            vectorStreams.add(inputStream_a);
            vectorStreams.add(inputStream_b);
            SequenceInputStream sis = new SequenceInputStream(vectorStreams.elements());
            OutputStream outputStream = new FileOutputStream(UPLOAD_DIR + "\\merge.txt");
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = sis.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            sis.close();
        } catch (Exception e) {
            return "Error merging files: " + e.getMessage();
        }
        return "index";
    }
    /*
     * 實(shí)現(xiàn)一個(gè)視頻文件切割成單個(gè)文件
     * RandomAccessFile可以在任意地方進(jìn)行讀寫文件
     * getFilePointer():返回文件記錄指針的當(dāng)前位置
     * seek(long pos):將文件記錄指針定位到pos位置
     **/
    @GetMapping("/splitVideo")
    public String splitVideo () {
        try {
            String UPLOAD_DIR = System.getProperty("user.dir");
            File source_file = new File(UPLOAD_DIR + "\\file.mp4");
            File chunk_file = new File(UPLOAD_DIR + "\\chunk");
            if(!chunk_file.exists()){
                chunk_file.mkdirs();
            }
            //切片大小設(shè)置為100kb
            long chunkSize = 102400;
            //分塊數(shù)量
            long chunkNum = (long) Math.ceil(source_file.length() * 1.0 / chunkSize);
            System.out.println("分塊總數(shù):"+chunkNum);
            //緩沖區(qū)大小
            byte[] b = new byte[1024];
            //使用RandomAccessFile訪問文件
            RandomAccessFile source_file_rf = new RandomAccessFile(source_file, "r");
            for (int i = 0; i < chunkNum; i++) {
                //創(chuàng)建分塊文件,如果存在刪除,在創(chuàng)建新建文件
                File file = new File(UPLOAD_DIR + "\\chunk\\" + i);
                if(file.exists()){
                    file.delete();
                }
                boolean newFile = file.createNewFile();
                // 創(chuàng)建成功,讀取原文件把流寫入到新建的新建文件中
                if (newFile) {
                    RandomAccessFile chunk_file_rf = new RandomAccessFile(file, "rw");
                    int len = -1;
                    while ((len = source_file_rf.read(b)) != -1) {
                        chunk_file_rf.write(b, 0, len);
                        if (file.length() >= chunkSize) {
                            break;
                        }
                    }
                    chunk_file_rf.close();
                }
            }
            source_file_rf.close();
        } catch (Exception e) {
            return "Error merging files: " + e.getMessage();
        }
        return "index";
    }
    /*
     * 實(shí)現(xiàn)多個(gè)視頻流合并成單個(gè)視頻文件
     **/
    @GetMapping("/mergVideo")
    public String mergVideo () {
        try {
            String UPLOAD_DIR = System.getProperty("user.dir");
            File origin_file = new File(UPLOAD_DIR + "\\file.mp4");
            File merge_file = new File(UPLOAD_DIR + "\\merge_file.mp4");
            File chunk_file = new File(UPLOAD_DIR + "\\chunk");
            if(merge_file.exists()) {
                merge_file.delete();
            }
            //創(chuàng)建新的合并文件
            merge_file.createNewFile();
            //使用RandomAccessFile讀寫文件
            RandomAccessFile raf_write = new RandomAccessFile(merge_file, "rw");
            //指針指向文件頂端
            raf_write.seek(0);
            //緩沖區(qū)
            byte[] b = new byte[1024];
            //分塊列表
            File[] fileArray = chunk_file.listFiles();
            // 轉(zhuǎn)成集合,便于排序
            List<File> fileList = Arrays.asList(fileArray);
            System.out.println("集合文件:" + fileList);
            // 從小到大排序
            Collections.sort(fileList, new Comparator<File>() {
                @Override
                public int compare(File o1, File o2) {
                    return Integer.parseInt(o1.getName()) - Integer.parseInt(o2.getName());
                }
            });
            System.out.println("排序的集合文件:" + fileList);
            // 遍歷集合文件,讀取每個(gè)文件的內(nèi)容再寫入到新文件中
            for (File chunkFile : fileList) {
                RandomAccessFile raf_read = new RandomAccessFile(chunkFile, "rw");
                int len = -1;
                while ((len = raf_read.read(b)) != -1) {
                    raf_write.write(b, 0, len);
                }
                raf_read.close();
            }
            raf_write.close();
            //校驗(yàn)文件
            FileInputStream fileInputStream = new FileInputStream(origin_file);
            FileInputStream mergeFileStream = new FileInputStream(merge_file);
            //取出原始文件的md5
            String originalMd5 = DigestUtils.md5Hex(fileInputStream);
            //取出合并文件的md5進(jìn)行比較
            String mergeFileMd5 = DigestUtils.md5Hex(mergeFileStream);
            if (originalMd5.equals(mergeFileMd5)) {
                System.out.println("合并文件成功");
            } else {
                System.out.println("合并文件失敗");
            }
        } catch (Exception e) {
            return "Error merging files: " + e.getMessage();
        }
        return "index";
    }
    /*
     * 實(shí)現(xiàn)前后端視頻文件的斷點(diǎn)續(xù)傳功能
     * Vector作用和數(shù)組類似,存儲數(shù)據(jù),功能會比數(shù)組強(qiáng)大,如: 可以返回枚舉類型數(shù)據(jù)
     * 注釋:SequenceInputStream參數(shù)必須是枚舉類型的數(shù)據(jù)
     * vectorStreams.elements()返回此向量的組件的枚舉
     **/
    @PostMapping("/merge-files")
    public String mergeFiles(@RequestParam MultipartFile file, @RequestParam Integer index, @RequestParam Integer total, @RequestParam String name) {
        try {
            InputStream inputStream = file.getInputStream();
            vectorStreams.add(inputStream);
            if (index < total) {
                return "success" + index;
            } else {
                SequenceInputStream sis = new SequenceInputStream(vectorStreams.elements());
                // 假設(shè)你想把合并后的流保存為一個(gè)新文件
                String UPLOAD_DIR = System.getProperty("user.dir");
                File outfile = new File(UPLOAD_DIR + "\\" + name);
                FileOutputStream fos = new FileOutputStream(outfile);

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = sis.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
                sis.close();
                fos.close();
                vectorStreams.clear();
                return "success";
            }
        } catch (Exception e) {
            return "Error merging files: " + e.getMessage();
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容