ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

sprongboot实现分段上传

2022-07-26 09:33:44  阅读:129  来源: 互联网

标签:文件 分段 upload sprongboot file 分片 上传 log


文件上传下载

断点续传,增量上传等

导入依赖

<!--jdk提供的关于文件上传-->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.10.0</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>
<!--apache提供了的文件上传-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.14</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

前端配置

前端使用的是webuploader

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webuploader</title>
</head>
<!--引入CSS-->
<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/webuploader/0.1.1/webuploader.css">
<style>
    #upload-container, #upload-list{width: 500px; margin: 0 auto; }
    #upload-container{cursor: pointer; border-radius: 15px; background: #EEEFFF; height: 200px;}
    #upload-list{height: 800px; border: 1px solid #EEE; border-radius: 5px; margin-top: 10px; padding: 10px 20px;}
    #upload-container>span{widows: 100%; text-align: center; color: gray; display: block; padding-top: 15%;}
    .upload-item{margin-top: 5px; padding-bottom: 5px; border-bottom: 1px dashed gray;}
    .percentage{height: 5px; background: green;}
    .btn-delete, .btn-retry{cursor: pointer; color: gray;}
    .btn-delete:hover{color: orange;}
    .btn-retry:hover{color: green;}
</style>
<!--引入JS-->
<body>
    <div id="upload-container">
        <span>点击或将文件拖拽至此上传</span>
    </div>
    <div id="upload-list">
        <!-- <div class="upload-item">
            <span>文件名:123</span>
            <span data-file_id="" class="btn-delete">删除</span>
            <span data-file_id="" class="btn-retry">重试</span>
            <div class="percentage"></div>
        </div> -->
    </div>
    <button id="picker" style="display: none;">点击上传文件</button>
</body>
<script src="http://lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js"></script>
<script src="https://cdn.bootcss.com/webuploader/0.1.1/webuploader.js"></script>
<script>
    $('#upload-container').click(function(event) {
        $("#picker").find('input').click();
    });
    var uploader = WebUploader.create({
        auto: true,// 选完文件后,是否自动上传。
        swf: 'https://cdn.bootcss.com/webuploader/0.1.1/Uploader.swf',// swf文件路径
        server: 'http://www.test.com/zyb.php',// 文件接收服务端。
        dnd: '#upload-container',
        pick: '#picker',// 内部根据当前运行是创建,可能是input元素,也可能是flash. 这里是div的id
        multiple: true, // 选择多个
        chunked: true,// 开起分片上传。
        threads: 5, // 上传并发数。允许同时最大上传进程数。
        method: 'POST', // 文件上传方式,POST或者GET。
        fileSizeLimit: 1024*1024*100*100, //验证文件总大小是否超出限制, 超出则不允许加入队列。
        fileSingleSizeLimit: 1024*1024*100, //验证单个文件大小是否超出限制, 超出则不允许加入队列。
        fileVal:'upload', // [默认值:'file'] 设置文件上传域的name。
    });

    uploader.on('fileQueued', function(file) {
        // 选中文件时要做的事情,比如在页面中显示选中的文件并添加到文件列表,获取文件的大小,文件类型等
        console.log(file.ext) // 获取文件的后缀
        console.log(file.size) // 获取文件的大小
        console.log(file.name);
        var html = '<div class="upload-item"><span>文件名:'+file.name+'</span><span data-file_id="'+file.id+'" class="btn-delete">删除</span><span data-file_id="'+file.id+'" class="btn-retry">重试</span><div class="percentage '+file.id+'" style="width: 0%;"></div></div>';
        $('#upload-list').append(html);
    });

    uploader.on('uploadProgress', function(file, percentage) {
        console.log(percentage * 100 + '%');
        var width = $('.upload-item').width();
        $('.'+file.id).width(width*percentage);
    });

    uploader.on('uploadSuccess', function(file, response) {
        console.log(file.id+"传输成功");
    });

    uploader.on('uploadError', function(file) {
        console.log(file);
        console.log(file.id+'upload error')
    });

    $('#upload-list').on('click', '.upload-item .btn-delete', function() {
        // 从文件队列中删除某个文件id
        file_id = $(this).data('file_id');
        // uploader.removeFile(file_id); // 标记文件状态为已取消
        uploader.removeFile(file_id, true); // 从queue中删除
        console.log(uploader.getFiles());
    });

    $('#upload-list').on('click', '.btn-retry', function() {
        uploader.retry($(this).data('file_id'));
    });

    uploader.on('uploadComplete', function(file) {
        console.log(uploader.getFiles());
    });
</script>
</html>

前端上传数据

#前台传输文件的表单信息
id: WU_FILE_1 文件ID
name: 录制_2021_03_19_08_52_06_801.mp4 #文件名
type: video/mp4 #类型
lastModifiedDate: Fri Mar 19 2021 08:52:22 GMT+0800 (中国标准时间)
size: 45711359 #大小
chunks: 9 #总分片数
chunk: 0  #当前分片的编号
upload: (binary)

断点续传[增量上传]

思路:前端会对文件进行分片并以此调用此接口,后台对文件进行保存。当判断文件时最后一个分片文件的时候对本地保存的文件进行组合。

@RequestMapping("/update")
public String update(HttpServletRequest request,MultipartFile files,
                     @RequestParam("chunks") Integer chunks,
                     @RequestParam("chunk") Integer chunk,
                     @RequestParam("name") String name){
    //根据原理,需要准备写的流os,写的位置locate,
    //分片临时位置tempLocate,当前分片数chunk[表单获取],总分片数chunks[表单获取],
    //文件名称name[表单获取],临时分片名称tempName
    String tempName = null, locate="E:\\file",tempLocate="E:\\file\\temp";
    BufferedOutputStream os = null;
    try {
        //----------------参数判断----------------
        if (name == null || chunk == null || chunks == null){
            log.error("参数未获取到");
            return "";
        }
        if (files == null){
            log.error("数据上传失败");
            return "";
        }
        //----------------断点续传----------------
        tempName = name+"_"+chunk;
        File assest = new File(tempLocate,tempName);
        //文件不存在再写,实现断点续传
        if (!assest.exists()){
            files.transferTo(assest);
        }
        //----------------合并数据----------------
        long curTime = System.currentTimeMillis();
        if (chunk == chunks-1){
            File file = new File(locate,name);
            os = new BufferedOutputStream(new FileOutputStream(file));

            for (int i = 0; i < chunks; i++) {
                File temp = new File(tempLocate,name+"_"+i);
                while (!temp.exists()){
                    //if (System.currentTimeMillis() - curTime > waitTime){
                    //    return "合并时过长,请重新上传文件";
                    //}
                    Thread.sleep(100);
                }
                byte[] bytes = FileUtils.readFileToByteArray(temp);
                os.write(bytes);
                os.flush();
                temp.delete();
            }
            os.flush();
            return "上传文件成功";
        }
    }catch (Exception e) {
        log.warn("文件上传出错");
        return "文件上传错误,等待网页维护人员进行维护";
    } finally {
        try {
            if (os != null){
                os.close();
            }
        }catch (IOException e){
            log.info("文件上传流关闭失败");
        }
    }
    return "null";
}

分片下载

思路:前端支持分片,会在头信息中带有Range信息,内容为起始位置-结束位置。通过range读取文件传给前端

须知

  1. 范围读取
  2. 请求头编写

分片下载

@RequestMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response){
    File file = new File("E:\\file\\测试.mp4");
    if (!file.exists()){
        return;
    }

    //-----------------设置参数-----------------
    Long begin = 0l,//开始读取位置
    fileSize=file.length(),//内容长度
    end = fileSize - 1,//结束读取位置
    curSize = 0l;//本次读取分片的大小
    BufferedOutputStream os = null;//写流
    RandomAccessFile is = null;//读流
    String fileName;//文件名称

    try {
        //-----------------设置文件的基础参数-----------------
        //获取文件名称
        fileName = file.getName();
        String range = request.getHeader("Range");
        //判断range:bytes=XXX-XXX
        if (range != null && range.contains("bytes=") && range.contains("-")){
            range = range.replaceAll("bytes=","").trim();
            String[] split = range.split("-");
            if (!StringUtils.hasLength(split[0])){
                //特殊情况1:-XXX
                end = Long.parseLong(split[1]);
            }else if (split.length == 1){
                //特殊情况2:XXX-
                begin = Long.parseLong(split[0]);
            }else if (split.length == 2){
                //理想情况
                begin = Long.parseLong(split[0]);
                end = Long.parseLong(split[1]);
                if (end > fileSize - 1){
                    end = fileSize - 1;
                }
            }
        }else {
            end = fileSize - 1;
        }
        curSize = end - begin + 1;
        //-----------------前端响应头设置-----------------
        //设置为下载
        response.setContentType("application/x-download");
        //设置下载文件的信息
        response.addHeader("Content-Disposition",
                           "attachment;filename="+new String(fileName.getBytes(),"ISO8859_1"));
        //支持分片下载
        response.setHeader("Accept-Ranges","bytes");
        //Content-Type 表示资源类型,如:文件类型
        response.setHeader("Content-Type", request.getServletContext().getMimeType(fileName));
        //设置文件大小
        response.setHeader("Content-Length",String.valueOf(curSize));
        //设置响应数据量:bytes [下载开始位置]-[结束位置]/[文件大小]
        response.setHeader("Content-Range","bytes "+begin+"-"+end+"/"+fileSize);
        //设置专门的响应类型
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        //自定义一些文件头
        response.setHeader("fileSize", String.valueOf(fileSize));
        response.setHeader("fileName", new String(fileName.getBytes(),"ISO8859_1"));

        //-----------------读写文件-----------------
        os = new BufferedOutputStream(response.getOutputStream());
        is = new RandomAccessFile(file,"r");
        byte[] buffer = new byte[1024];
        int len = 0;
        Long sum = 0l;//累计添加的流
        //跳过已经获取的
        is.seek(begin);
        while (sum<curSize){
            int readSize = buffer.length;
            if ((curSize-sum)<readSize){
                readSize = (int) (curSize-sum);
            }
            if ((len = is.read(buffer,0,readSize))==-1){
                break;
            }
            os.write(buffer,0,len);
            sum+=len;
        }
        log.info("下载成功");
    } catch (Exception e) {
        log.warn("下载出现错误");
    }finally {
        if (os != null){
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (is != null){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

分片下载合并

前端不好对文件进行分片的合并,需要后端进行合并处理

思路

  1. 通过JAVA模拟请求
  2. 将文件通过 FileUtils.readFileToByteArray(temp);读取合并

不进行延伸的原因

  1. 对于B/S结构,因为无法知道用户下载文件的具体位置,就无法进行合并
  2. 为了用户安全,每个分片下载都会进行提示,用户体验差

综合所述,除了C/S结构,本地端不建议使用

标签:文件,分段,upload,sprongboot,file,分片,上传,log
来源: https://www.cnblogs.com/musiro/p/16519674.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有