webuploader工具官网:http://fex.baidu.com/webuploader/

webuploader自行官网下载

博主项目GitHub地址:https://github.com/AnRan-727/webuploader

上传文件按钮Html

<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>

单文件分片上传Js

    代码示例:

<script type="text/javascript" src="../script/jquery.min.js"></script>
<script type="text/javascript" src="../script/oneJs/webuploader.js"></script>
<script type="text/javascript" src="../script/layer/layer.js"></script>
<script>
    var $list = $("#thelist");
    var $btn = $("#ctlBtn");
    var state = 'pending'; // 上传文件初始化
    var timer;
    var fileArray = [];
    var uploader = WebUploader.create({
        // 文件接收服务端。
        server: '/upload',
        pick: '#picker',
        // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
        resize: false,
        duplicate: true,
        chunked: true,
        threads: 5,
        chunkSize: 10485760
    });
    //点击上传之前调用的方法
    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 + '%');
    });
    var fileName = "";
    //文件成功、失败处理
    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('已上传');
        fileName = file.name;
        $.get("/merge", {"guid": successDuid}, function (data, status) {
            layer.msg(data+"上传完成");
        });
    });
    //文件上传出错
    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>

Controller控制层:

package com.liuyinlong.www.webuploader.webuploader.controller;
 
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
 
/**
 * Created by IntelliJ IDEA.
 * User: AnRan
 * Url: www.liuyinlong.com
 * Date: 2020/7/28
 */
@Controller
public class OneUploadController {
 
    private static String FILENAME = "";
 
    private static String FILEPATH = "";
 
    //正式文件路径
    @Value("${upload.file.path}")
    private String decryptFilePath;
 
    //临时文件路径  分片
    @Value("${upload.file.path.temp}")
    private String decryptFilePathTemp;
 
    /**
     * 分片上传单文件
     * @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) {
                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 {
        //获取分片文件路径
        File file = new File(decryptFilePathTemp+File.separator+guid);
        //判断是否是文件夹
        if (file.isDirectory()) {
            //得到该分片文件夹下的所有分片文件
            File[] files = file.listFiles();
            //判断是否为空
            if (files != null && files.length > 0) {
                //获取当前时间
                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter yyyymMdd = DateTimeFormatter.ofPattern("YYYYMMdd");
                String format = now.format(yyyymMdd);
                //设置路径为 本地目录+当前时间
                String filePath = decryptFilePath +"\\"+format;
                File file1 = new File(filePath);
                if(!file1 .exists()) { //当该文件夹不存在时
                    file1.mkdirs();//创建目录
                }
                //创建真实文件
                File partFile = new File(filePath + 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);
                //System.out.println();
                FILENAME = "";
            }
        }
    }
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注