SpringBoot WebUploader大文件分片上传

Posted 盲目的拾荒者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot WebUploader大文件分片上传相关的知识,希望对你有一定的参考价值。

后端技术:SpringBoot2.x

页面:freemarker

webuploader:http://fex.baidu.com/webuploader/getting-started.html

1.application.properties

server.port=9999
spring.freemarker.suffix=.html
#上传文件存放目录
xdja.upload.file.path=/home/xdja/
#临时文件存放目录
xdja.upload.file.path.temp=/home/temp
##最大上传文件
spring.servlet.multipart.max-file-size=3072MB
spring.servlet.multipart.max-request-size=3072MB
技术图片

2.前端代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">

    <title>隔离交换系统解密</title>
    <link rel="stylesheet" type="text/css" href="themes/bootstrap.min.css"/>
    <link rel="stylesheet" href="themes/webuploader.css">
    <script type="text/javascript" src="script/jquery.min.js"></script>
    <script type="text/javascript" src="script/webuploader.js"></script>


    <!--layer弹出框-->
    <link rel="stylesheet" href="script/layer/mobile/need/layer.css">
    <script type="text/javascript" src="script/layer/layer.js"></script>

    <style type="text/css">

        .wu-example {
            width: 847px;

            position: relative;
            padding: 45px 15px 15px;
            margin: 0 auto;
            background-color: #fafafa;
            box-shadow: inset 0 3px 6px rgba(0, 0, 0, .05);
            border-color: #e5e5e5 #eee #eee;
            border-style: solid;
            border-width: 1px 0;
        }

        #picker {
            display: inline-block;
            line-height: 1.428571429;
            vertical-align: middle;
            margin: 0 12px 0 0;
        }
    </style>
</head>
<body>

<div class="alert alert-success" role="alert" style="text-align: center;font-size: 18px;">隔离交换系统可视化解密</div>

<div id="uploader" class="wu-example">
    <!--用来存放文件信息-->
    <div id="thelist" class="uploader-list"></div>
    <div class="btns">
        <div id="picker">选择文件</div>
        <button id="ctlBtn" class="btn btn-default">开始上传</button>
    </div>
    <p>
        <span>上传所用时间:</span>
        <span id="useTime">0</span>s
    </p>
</div>


<script type="text/javascript">
    var $list = $("#thelist");
    var $btn = $("#ctlBtn");
    var state = ‘pending‘; // 上传文件初始化
    var timer;
    var fileArray = [];

    var uploader = WebUploader.create({

        // swf文件路径
        /*  swf: BASE_URL + ‘/js/Uploader.swf‘,*/

        // 文件接收服务端。
        server: ‘upload‘,

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建,可能是input元素,也可能是flash.
        pick: ‘#picker‘,

        // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
        resize: false,
        duplicate: true,
        chunked: true,
        threads: 5,
        chunkSize: 10485760,
        formData: {
            guid: ""
        }
    });

    //点击上传之前调用的方法
    uploader.on("uploadStart", function (file) {
        var guid = WebUploader.Base.guid();
        var paramOb = {"guid": guid, "filedId": file.source.ruid}
        uploader.options.formData.guid = guid;
        fileArray.push(paramOb);
    });

    // 当有文件被添加进队列的时候
    uploader.on(‘fileQueued‘, function (file) {
        $list.append(‘<div id="‘ + file.id + ‘" class="item">‘ +
            ‘<h4 class="info">‘ + file.name + ‘</h4>‘ +
            ‘<p class="state">等待上传...</p>‘ +
            ‘</div>‘);
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.on(‘uploadProgress‘, function (file, percentage) {
        var $li = $(‘#‘ + file.id),
            $percent = $li.find(‘.progress .progress-bar‘);
        // 避免重复创建
        if (!$percent.length) {
            $percent = $(‘<div class="progress progress-striped active">‘ +
                ‘<div class="progress-bar" role="progressbar" style="width: 0%">‘ +
                ‘</div>‘ +
                ‘</div>‘).appendTo($li).find(‘.progress-bar‘);
        }
        $li.find(‘p.state‘).text(‘上传中‘);
        $percent.css(‘width‘, percentage * 100 + ‘%‘);
    });
    //文件成功、失败处理
    uploader.on(‘uploadSuccess‘, function (file) {
        var successFileId = file.source.ruid;
        var successDuid;
        if (fileArray.length > 0) {
            for (var i = 0; i < fileArray.length; i++) {
                if (fileArray[i].filedId === successFileId) {
                    successDuid=fileArray[i].guid;
                    fileArray.splice(i, 1);
                }
            }
        }
        clearInterval(timer);
        $(‘#‘ + file.id).find(‘p.state‘).text(‘已上传‘);
        $.get("merge", {"guid": successDuid}, function (data, status) {
            layer.msg("合并完成");
        });

    });

    uploader.on(‘uploadError‘, function (file) {
        $(‘#‘ + file.id).find(‘p.state‘).text(‘上传出错‘);
    });

    uploader.on(‘uploadComplete‘, function (file) {
        $(‘#‘ + file.id).find(‘.progress‘).fadeOut();
    });

    $btn.on(‘click‘, function () {
        if (state === ‘uploading‘) {
            uploader.stop();
        } else {
            uploader.upload();
            timer = setInterval(function () {
                var useTime = parseInt($("#useTime").html());
                useTime = useTime + 1;
                $("#useTime").html(useTime);
            }, 1000);
        }
    });


</script>
</body>
</html>
技术图片

页面效果:

访问:http://localhost:9999/webuploader

技术图片技术图片?

后台java代码:

    private static String FILENAME = "";


    @Value("${xdja.upload.file.path}")
    private String decryptFilePath;

    @Value("${xdja.upload.file.path.temp}")
    private String decryptFilePathTemp;

    @GetMapping("/webuploader")
    public String webuploader() {
        return "webupload";
    }
    
    /**
     * 分片上传
     *
     * @return ResponseEntity<Void>
     */
    @PostMapping("/upload")
    @ResponseBody
    public ResponseEntity<Void> decrypt(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file, Integer chunks, Integer chunk, String name, String guid) throws IOException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            if (file == null) {
                throw new ServiceException(ExceptionEnum.PARAMS_VALIDATE_FAIL);
            }
            System.out.println("guid:" + guid);
            if (chunks == null && chunk == null) {
                chunk = 0;
            }
            File outFile = new File(decryptFilePathTemp+File.separator+guid, chunk + ".part");
            if ("".equals(FILENAME)) {
                FILENAME = name;
            }
            InputStream inputStream = file.getInputStream();
            FileUtils.copyInputStreamToFile(inputStream, outFile);
        }
        return ResponseEntity.ok().build();
    }

   /**
     * 合并所有分片
     *
     * @throws Exception Exception
     */
    @GetMapping("/merge")
    @ResponseBody
    public void byteMergeAll(String guid) throws Exception {
        System.out.println("merge:"+guid);
        File file = new File(decryptFilePathTemp+File.separator+guid);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                File partFile = new File(decryptFilePath + File.separator + FILENAME);
                for (int i = 0; i < files.length; i++) {
                    File s = new File(decryptFilePathTemp+File.separator+guid, i + ".part");
                    FileOutputStream destTempfos = new FileOutputStream(partFile, true);
                    FileUtils.copyFile(s, destTempfos);
                    destTempfos.close();
                }
                FileUtils.deleteDirectory(file);
                FILENAME = "";
            }

        }


    }
技术图片

经过测试1.35G 分片上传大概需要30s

源码地址:https://gitee.com/niugangxy/webuploader

                                                                        微信公众号

                                               技术图片技术图片?

                                                                             JAVA程序猿成长之路

                          分享资源,记录程序猿成长点滴。专注于Java,Spring,SpringBoot,SpringCloud,分布式,微服务。 

以上是关于SpringBoot WebUploader大文件分片上传的主要内容,如果未能解决你的问题,请参考以下文章

springboot2.0结合webuploader实现文件分片上传

百度Fex webuploader.js上传大文件失败

WebUploader上传大文件时,上传出错问题

用webuploader怎么解决跨域上传文件的问题

WebUploader 大文件上传解决方案(500M以上)

webuploader 大文件分片上传处理