利用webupload实现分片上传文件

1.前端js代码

function update() {
    var $container = $('#fileContainer');
    var $fileName = $container.find('.file-name');
    var $fileSize = $container.find('.file-size');
    var uploader = WebUploader.create({
    	// 文件接收服务端。
    	server: '/test/import',
    	// 选择文件的按钮。可选。
    	// 内部根据当前运行是创建,可能是input元素,也可能是flash.
    	pick: {
        	id: '#picker',
        	multiple: false //限制多文件上传
    	},
    	chunked: true, //开启分片上传
    	chunkSize: 5242880, //如果要分片,分多大一片,默认5M
    	// dnd: "#drag_box", //设置可拖拽上传容器
    	accept: {
        	title: 'Zip,excel',
        	extensions: 'zip,xls,xlsx',
        	mimeTypes: 'application/zip,application/x-zip,application/x-zip-compressed,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    	}, //设置文件类型限制
    	fileNumLimit: 1 //设置文件数量限制
    });

    //当有文件被选择上传时,因为只上传1个文件所以多次选择之前先清空之前的选择实现覆盖
    uploader.on('beforeFileQueued', function () {
        if (currentStep != '02') {
            return false
        }
        console.log("beforeFileQueued")
        uploader.reset();
        $fileName.html('模板名称');
        $fileName.html('');
        $('#step02Btn').removeClass('active');
        $container.removeClass('active');
        $('#update-result').html('').removeClass('success').removeClass('error');
    });
    var fileSize = 0;
    var lastUpdatedSize = 0;
    var lastUpdateTime = 0;
    // 当有文件被添加进队列的时候
    uploader.on('fileQueued', function (file) {
        console.log("fileQueued::", file)
        const name = file.name;
        const size = file.size;
        fileSize = size;
        $fileName.html(name);
        $fileSize.html(cleanSize(size));
        uploader.upload();
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.on('uploadProgress', function (file, percentage) {
        // console.log("uploadProgress::", percentage);
        const perNumber = parseInt(percentage * 100);
        const per = perNumber + '%';

        $('.updateProgress').find('.text').html(per).css('margin-left', Math.min(200, Math.max(0, 2.4 *
            perNumber - 30)));
        $('#updateProgressBar').css('width', per);
    });
    uploader.on('uploadSuccess', function (file, data) {
        console.log('uploadSuccess::', data);
        //data参数即为服务器响应数据
        if (data.resCode === 1) {
            setTimeout(function () {
                $('#update-result').html('上传成功').addClass('success').removeClass(
                    'error');
            }, 600)
            currentStep = '02';
            renderStep();
            $('#step02Btn').addClass('active');
            var $container = $('#fileContainer');
            $container.addClass('active');
        } else {
            $('#update-result').html(data.msg).addClass('error').removeClass('success');
        }
    });

    // 开始上传
    uploader.on('startUpload', function () {
        console.log("startUpload::");
        $('#picker').hide();
        $('.file-loading-but').show();
        $('.updateProgress').fadeIn();
        lastUpdateTime = new Date().getTime();
    })
    uploader.on('uploadError', function (file) {
        console.log('uploadError::', data);
        $('#update-result').html('上传出错了').addClass('error').removeClass('success');
    });
    uploader.on('uploadComplete', function (file) {
        console.log('uploadComplete::');
        $('.updateProgress').fadeOut();
        $('#picker').show();
        $('.file-loading-but').hide();
        setTimeout(function () {
            $('#updateProgressBar').css('width', 0);
        }, 500)
    });

    function cleanSize(size) {
        if (size < 1024 * 1024) {
            return parseInt(size / 1024) + 'KB'
        } else {
            return parseFloat(size / 1024 / 1024).toFixed(2) + 'M'
        }
    }
}

2.后端接收分片代码:

/**
 * 接收分片
 */
@PostMapping("import")
public String import(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file, Integer chunks, Integer chunk, String name, String guid) {
	String tempDir= test;
	//获取当前工作路径
    String workPath = System.getProperty("user.dir");
    File workFile = new File(workPath);
    NOWPATH = workFile.getParent();

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        if (file == null) {
            return JSONUtil.toJSONStringContainNullAttribute(Result.commonFail("文件不存在或发生未知错误,请重新选择"));
        }
        logger.info("guid:" + guid);
        if (chunks == null && chunk == null) {
            chunk = 0;
        }
        File outFile = new File(NOWPATH+FILEDIRNAME+tempDir+"/"+File.separator+guid, chunk + ".part");
        if ("".equals(IMPORTFILENAME)) {
        	//把文件名保存到全局变量(项目中可以保存到redis中缓存)
            IMPORTFILENAME = name;
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            FileUtils.copyInputStreamToFile(inputStream, outFile);
        } catch (IOException e) {
            e.printStackTrace();
            return JSONUtil.toJSONStringContainNullAttribute(Result.commonFailJson("上传失败"));
        }

        logger.info("文件所在位置:"+NOWPATH+FILEDIRNAME+tenantId+"/"+File.separator+guid);
    }
    return JSONUtil.toJSONStringContainNullAttribute(Result.commonSuccess("上传成功"));

}

3.合并分片:

@GetMapping("/merge")
public String byteMergeAll(@RequestParam(value = "guid",required = false) String guid,HttpServletRequest req) {
    try {
        logger.info("开始合并分片····");
        String realPath = NOWPATH+FILEDIRNAME+tempDir+"/";
        File file = new File(realPath +File.separator+guid);
        //合并后文件的名字
        String lastFileName = "";
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                File partFile = new File(realPath + File.separator + IMPORTFILENAME);
                lastFileName = partFile.getName();
                for (int i = 0; i < files.length; i++) {
                    File s = new File(realPath +File.separator+guid, i + ".part");
                    FileOutputStream destTempfos = new FileOutputStream(partFile, true);
                    FileUtils.copyFile(s, destTempfos);
                    destTempfos.flush();
                    destTempfos.close();
                }
                FileUtils.deleteDirectory(file);
                IMPORTFILENAME = "";
            }
        }
        logger.info("分片合并结束");
    }catch (Exception e){
        logger.info("上传失败:"+e.getMessage());
        return JSONUtil.toJSONStringContainNullAttribute(Result.commonFail("导入数据失败"));
    }

    return JSONUtil.toJSONStringContainNullAttribute(Result.commonFail("上传的文件有误,请核实后重新上传"));
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值