使用dropzone实现文件拖拽上传功能

1,203 阅读1分钟

前端代码,关于dropzone的配置我写在注释里了

<html>
<head>
    <meta charset="utf-8" />
    <%@include file="/webmana/meta.jsp" %>
    <title></title>
    <link rel="stylesheet" type="text/css" href="${ctx }/common/static/dropzone/dropzone.css"/>
    <link rel="stylesheet" type="text/css" href="${ctx }/common/static/dropzone/basic.css"/>
    <style type="text/css">
        .dropzone{
            border:3px dashed #ddd;margin:20px;
            border-radius:5px;

        }
    </style>
</head>
<body>
    <div class="cl pd-5 bg-1 bk-gray mt-20">
        <input type="hidden" name="classId" value="${classId}"/>
        <span class="l">
            <a href="javascript:;" id="qr" class="btn btn-primary radius">
                <i class="Hui-iconfont"></i>提交
            </a>
            <a href="javascript:;" id="cancel" class="btn btn-primary radius">
                <i class="Hui-iconfont"></i>取消
            </a>
            <a href="javascript:;" onclick="uploadImg1()" class="btn btn-primary radius">
                <i class="Hui-iconfont"></i>关闭
            </a>
        </span>
    </div>
    <div id="dropz" class="dropzone">
        <div id="pro"></div>
        <div id="speed"></div>
        <div id="time"></div>
    </div>

    <input type="hidden" name="file" id="file"/>
<%@include file="/webmana/footer.jsp" %>

<script>
    function uploadImg1(){
        parent.location.reload();
        layer_close()
    }
    Dropzone.autoDiscover = false
    $("#dropz").dropzone({   //配置dropzone
        url: "${ctx}/webmana/uploadImg",   //文件上传的路径
        method:"post",
        maxFiles: 100,  //一次上传的量
        maxFilesize: 1024,   //M为单位
        //acceptedFiles: ".jpg,.jpeg,.doc,.docx,.ppt,.pptx,.txt,.avi,.pdf,.mp3,.zip", //可接受的上传类型
        acceptedFiles: ".jpg,.jpeg,.png",
        //autoProcessQueue: true,     //是否自动上传,false时需要触发上传
        parallelUploads: 100,  //手动触发时一次最大可以上传多少个文件
        paramName: "file",          //后台接受文件参数名
        addRemoveLinks:true,
        filesizeBase: 1024,
        //uploadMultiple:true,  //建议不要使用,否则保存不了文件
        dictDefaultMessage: "拖入需要上传的文件",      //上传框默认显示文字
        dictMaxFilesExceeded: "您最多只能上传10个文件!",
        dictResponseError: '文件上传失败!',
        dictInvalidFileType: "你不能上传该类型文件,文件类型只能是*.jpg,*.gif,*.png。",
        dictFallbackMessage:"浏览器不受支持",
        dictFileTooBig:"文件过大上传文件最大支持.",
        init: function () {
            var mm = (new Date()).getTime();
            var alreadyUpload=0;
            var myDropzone = this, submitButton = document.querySelector("#qr"),
                    cancelButton = document.querySelector("#cancel");
            myDropzone.on('addedfile', function (file) {
                //添加上传文件的过程,可再次弹出弹框,添加上传文件的信息

            });
            myDropzone.on('sending', function (data, xhr, formData) {
                //向后台发送该文件的参数
                formData.append('classId', jQuery('input[name=classId]').val());
            });
            myDropzone.on('success', function (files, response) {
                //文件上传成功之后的操作
            });
            myDropzone.on('error', function (files, response) {
                //文件上传失败后的操作
            });
            //上传过程
            myDropzone.on('totaluploadprogress', function (progress, byte, bytes) {
                //console.log(byte)
                //progress为进度百分比
                $("#pro").text("上传进度:" + parseInt(progress) + "%");
                //计算上传速度和剩余时间
                var mm1=(new Date()).getTime();
                var timecha=(mm1-mm)/1000;  //时间差
                mm=mm1;
                var uploadcha=bytes-alreadyUpload;      //上传文件差
                alreadyUpload=bytes;
                var speed;
                var remain;
                var byteKb = byte/1024;
                var bytesKb = bytes/1024;
                var byteMb = byte/1024/1024;
                var bytesMb = bytes/1024/1024;

                if(byteKb <= 1024){
                    speed = (uploadcha)/(1024*timecha).toFixed(2) ;
                    remain=(byte - bytes)/1024;
                    $("#dropz #speed").text("上传速率:" + speed+ " KB/s");
                }else{
                    speed = (uploadcha/(1024*1024*timecha)).toFixed(2) ;
                    remain=(byte - bytes)/1024/1024;
                    $("#dropz #speed").text("上传速率:" + speed+ " MB/s");
                }

                $("#dropz #time").text("剩余时间:"+arrive_timer_format(parseInt(remain/speed)));
                if(bytes >= byte){
                    if(byteKb <= 1024){
                        $("#dropz #speed").text("上传速率:0 KB/s");
                    }else{
                        $("#dropz #speed").text("上传速率:0 MB/s");
                    }
                    $("#dropz #time").text("剩余时间:0:00:00");
                }
            });
            submitButton.addEventListener('click', function () {
                //点击上传文件
                myDropzone.processQueue();
                //myDropzone.enqueueFiles(myDropzone.getAcceptedFiles());
                //myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED))
            });
            cancelButton.addEventListener('click', function () {
                //取消上传
                myDropzone.removeAllFiles();
            });
        }
    });
    //剩余时间格式转换:
    function arrive_timer_format(s) {
        var t;
        if(s > -1){
            var hour = Math.floor(s/3600);
            var min = Math.floor(s/60) % 60;
            var sec = s % 60;
            var day = parseInt(hour / 24);
            if (day > 0) {
                hour = hour - 24 * day;
                t = day + "day " + hour + ":";
            }
            else t = hour + ":";
            if(min < 10){t += "0";}
            t += min + ":";
            if(sec < 10){t += "0";}
            t += sec;
        }
        return t;
    }
</script>
</body>
</html>

注意:

autoProcessQueue为true时默认自动上传所有文件,而设为false时手动触发默认一次只传两个,

设置parallelUploads: 100,可修改手动触发一次上传的数量

 

java后台接收保存文件:

@RequestMapping(value = "uploadImg", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String uploadImg(
            @RequestParam(value = "file") MultipartFile[] files,  //这样接收文件
            String classId,
            HttpServletRequest request
    ) {
        try {
            Map<String,Object> params=new HashMap<String, Object>();
            String path="/resource/images/";
            int userId=((TSystemUser)request.getSession().getAttribute("USER")).getUserId();
            params.put("classId",classId);
            params.put("attachmentType","IMAGE");
            params.put("userId",userId);
            for (MultipartFile file : files) {    //循环保存文件
                Map<String,String> name=uploadFile(file, request);
                params.put("attachmentUrl",path+name.get("saveName"));
                params.put("attachmentName",name.get("fileName"));
                attachmentService.saveFile(params);
               // attachmentService.saveImg(path);
            }
            // 返回前台
            return JSON.toJSONString("success");

        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString("fail");
        }

    }

    public Map<String,String> uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        Map<String,String> result=new HashMap<String,String>();
        String fileName = file.getOriginalFilename();
        String basePath=request.getSession().getServletContext().getRealPath("/");
        String path=basePath+"resource/images/";            //设置文件保存路径
//        File tempFile = new File(path, new Date().getTime() + String.valueOf(fileName));
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
        String saveName=String.valueOf((new Date()).getTime()).substring(8)+(int)((Math.random()*999+1))+'.'+fileType;

        File tempFile = new File(path, String.valueOf(saveName));
        if (!tempFile.getParentFile().exists()) {    //创建文件夹
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        file.transferTo(tempFile);
        result.put("fileName",fileName);
        result.put("saveName",saveName);
        return result;
    }