欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用 dropzone 多文件上传的 java

最编程 2024-06-23 11:57:03
...

DropzoneJS是一个提供文件拖拽上传并且提供图片预览的开源类库, 它是轻量级的,不依赖任何其他类库(如JQuery)并且高度可定制.文档官网https://www.dropzonejs.com/.

java利用dropzone多文件上传案例效果图

  • html页面

使用dropzone的典型方式是通过创建一个 class 属性中包含 dropzone的form表单元素

<form action="#" class="dropzone dropzone-file-area" id="my-dropzone" enctype="multipart/form-data" method="post">
    <span >
        <i class="fa fa-upload"></i>
        <font style="color: red">点击框内空白区域进行上传</font>
    </span>
</form>
<button  class="login-button" onclick="uploadAllFile();" style="margin-top: 5px;">確認全部上傳</button>
  • 引入dropzone.min.css样式
<link rel="stylesheet" type="text/css" href="${webAppPath}/static/comp/dropzone/basic.min.css">
<link rel="stylesheet" type="text/css" href="${webAppPath}/static/comp/dropzone/dropzone.min.css">

额外新加的css样式

<style>
        .login-button { /* 按钮美化 */
            width: 270px; /* 宽度 */
            height: 40px; /* 高度 */
            border-width: 0px; /* 边框宽度 */
            border-radius: 3px; /* 边框半径 */
            background: #1E90FF; /* 背景颜色 */
            cursor: pointer; /* 鼠标移入按钮范围时出现手势 */
            outline: none; /* 不显示轮廓线 */
            font-family: Microsoft YaHei; /* 设置字体 */
            color: white; /* 字体颜色 */
            font-size: 17px; /* 字体大小 */
        }
        .login-button:hover { /* 鼠标移入按钮范围时改变颜色 */
            background: #5599FF;
        }
    </style>
  • 下载并引入dropzone.js
<script type="text/javascript" src="${webAppPath}/static/comp/dropzone/dropzone.min.js"></script>

 

初始化dropzone控件

功能选项

url:最重要的参数,指明了文件提交到哪个页面。 
method:默认为post,如果需要,可以改为put。 
paramName:相当于元素的name属性,默认为file。 
maxFilesize:最大文件大小,单位是 MB。 
maxFiles:默认为null,可以指定为一个数值,限制最多文件数量。 
addRemoveLinks:默认false。如果设为true,则会给文件添加一个删除链接。 
acceptedFiles:指明允许上传的文件类型,格式是逗号分隔的 MIME type 或者扩展名。例如:image/*,application/pdf,.psd,.obj 
uploadMultiple:指明是否允许 Dropzone 一次提交多个文件。默认为false。如果设为true,则相当于 HTML 表单添加multiple属性。 
headers:如果设定,则会作为额外的 header 信息发送到服务器。例如:{“custom-header”: “value”} 
init:一个函数,在 Dropzone 初始化的时候调用,可以用来添加自己的事件监听器。 
forceFallback:Fallback 是一种机制,当浏览器不支持此插件时,提供一个备选方案。默认为false。如果设为true,则强制 fallback。 
fallback:一个函数,如果浏览器不支持此插件则调用。 

dictDefaultMessage:没有任何文件被添加的时候的提示文本。 
dictFallbackMessage:Fallback 情况下的提示文本。 
dictInvalidInputType:文件类型被拒绝时的提示文本。 
dictFileTooBig:文件大小过大时的提示文本。 
dictCancelUpload:取消上传链接的文本。 
dictCancelUploadConfirmation:取消上传确认信息的文本。 
dictRemoveFile:移除文件链接的文本。 
dictMaxFilesExceeded:超过最大文件数量的提示文本。 

常用事件

以下事件接收 file 为第一个参数

addedfile:添加了一个文件时发生。 
removedfile:一个文件被移除时发生。你可以监听这个事件并手动从服务器删除这个文件。 
uploadprogress:上传时按一定间隔发生这个事件。第二个参数为一个整数,表示进度,从 0 到 100。第三个参数是一个整数,表示发送到服务器的字节数。当一个上传结束时,Dropzone 保证会把进度设为 100。注意:这个函数可能被以同一个进度调用多次。 
success:文件成功上传之后发生,第二个参数为服务器响应。 
complete:当文件上传成功或失败之后发生。 
canceled:当文件在上传时被取消的时候发生。 
maxfilesreached:当文件数量达到最大时发生。 
maxfilesexceeded:当文件数量超过限制时发生。 

<script type="text/javascript">
    var myDropzone;//上传文件对象
    var signFileName = [];//上次,文件名称
    var fileUrl = [];
    $(function(){
        //禁止对所有元素的自动查找:
        Dropzone.autoDiscover = false;
        //加载上传控件
        $("#my-dropzone").dropzone({
            url: "${webAppPath}/upload_file_json",
            method : "post",
            paramName : "myFiles", // 默认为file
            parallelUploads: 20, //最大并行处理量
            maxFiles : 20,// 一次性上传的文件数量上限
            uploadMultiple : true,//多文件上传
            autoProcessQueue : false,// 自动上传 默认为 true
            maxFilesize : 1, // MB
            addRemoveLinks:true, //添加删除按钮
            acceptedFiles : ".jpg,.png,.jpeg.JPG,.PNG,.JPEG", // 上传的类型
            dictMaxFilesExceeded : "您最多只能上传{{maxFiles}}个文件!",
            dictResponseError : '文件上传失败!',
            dictInvalidFileType : "你不能上传该类型文件,文件类型只能是*.jpg,*.png,*.jpeg,*.JPG,*.PNG,*.JPEG",
            dictFallbackMessage : "浏览器不受支持",
            dictFileTooBig:"文件过大({{filesize}}MB). 上传文件最大支持: {{maxFilesize}}MB.",
            dictRemoveFile: "删除",
            dictDefaultMessage:"",
            init : function() {
                myDropzone = this;
                this.on("addedfile", function(file) {
                    // 上传文件时触发的事件
                    //console.log("添加文件"+file.name);
                    var fileName = file.name;
                    if(signFileName != null && signFileName.length > 0){
                        signFileName.push(fileName);
                    }else{
                        // 上传文件存在,就删除
                        if(signFileName.join(",").indexOf(fileName) != -1){
                            this.removeFile(file);
                        }else{
                            signFileName.push(fileName);
                        }
                    }
                });
                this.on("queuecomplete", function(file) {
                    // 上传完成后触发的方法
                    updateItemImg(signFileName,fileUrl);
                });
                this.on("removedfile", function(file) {
                    // 删除文件时触发的方法
                    var fileName = file.name;
                    signFileName = $.grep(signFileName, function(value) {
                        return value != fileName;
                    });
                });
                this.on("error", function(file,msg,xhr){
                    console.log("file upload error!!");

                });
                this.on("maxfilesexceeded", function(file){
                    //当文件数量超过限制时发生
                    //删除超过限制的文件
                    layer.alert("上傳圖片數量一次性不能超過20張");
                    this.removeFile(file);
                });
                this.on("success", function(file, result){
                    fileUrl = result.url;
                });
            }
        });

    })
    var index = "";
    function uploadAllFile() {
        if(signFileName.length > 0){
            index = layer.load(0, {shade: false}); //0代表加载的风格,支持0-2
            myDropzone.processQueue();// 提交队列中的文件
        }else{
            layer.alert("請先選擇圖片");
        }
    }

    function updateItemImg(signFileName,fileUrl){
        var itemCodes = "";
        var urls = "";
        for(var i in signFileName){
            itemCodes += signFileName[i].split('\.')[0]+",";
        }
        for(var k in fileUrl){
            urls += fileUrl[k]+",";
        }
        $.ajax({
            url: "${webAppPath}/posItem/updateItemImgUrl",
            method: 'POST',
            dataType: 'json',
            data: {
                "itemCodes":itemCodes,
                "urls":urls
            },
            success: function (data) {
                layer.close(index);
                if(data.flag){
                    layer.alert(data.msg, {
                        skin: 'layui-layer-molv' //样式类名
                        ,closeBtn: 0
                    }, function(){
                        window.location.href='${webAppPath}'+'/posKeydesc/newList';
                    });
                }else{
                    layer.alert(data.msg)
                }
            }
        })
    }
</script>
  • Java后台文件上传代码
 @RequestMapping("/upload_file_json")
    public Object upload_media(StandardMultipartHttpServletRequest req, HttpServletResponse rsp) {
        try {
            String dirName = Objects.toString(req.getParameter("dir"), "image");
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            String currCompany = (String) session.getAttribute("currCompany");
            if(AppUtils.isBlank(currCompany)){
                ModelAndView errorMv = new ModelAndView("/redirect:/403");
                errorMv.addObject("message", "缺少公司慘數");
                return errorMv;
            }
            //文件保存目錄路徑
            //rootPath/dirPath/dirName/ymdPath/fileName
            String ymdPath = DateUtils.formatDate(new Date(), "yyyy_MM_dd") + "/";
            String dirPath = "/" + currCompany + "/";
            String rootPath = FileConfigUtils.getImagesSavePath();
            String os = System.getProperty("os.name");
            if (os.toLowerCase().startsWith("linux")) {
                //rootPath = SystemManager.inst().upload_path;
            }
            String filePath = dirPath + dirName + "/" + ymdPath;
            /*新文件名字的命名規則**/
            Function<String, String> nameFunc = fileName -> {
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();//檢查後綴名
                String newFileName = IDManager.generateID();
                return newFileName + "." + fileExt;
            };

            rsp.setContentType("text/html; charset=UTF-8");

            if (!ServletFileUpload.isMultipartContent(req)) {
                return getError("請選擇文件。");
            }

            //檢查目錄
            File uploadDir = new File(rootPath);
            //檢查目錄
           /* if(!uploadDir.isDirectory()){
                System.out.println("上傳目錄不存在。");
                return getError("上傳目錄不存在.");
            }*/
            //檢查目錄寫權限
            if (!uploadDir.canWrite()) {
                System.out.println("上傳目錄沒有寫權限。");
                return getError("上傳目錄沒有寫權限。");
            }

            List<String> url = upload_multi_file(rootPath, filePath, nameFunc, req);
            System.out.println("************富文本框上傳圖片地址************" + url);
            JSONObject ret = new JSONObject();
            ret.put("error", 0);
            ret.put("url", url);

            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            return getError("未知錯誤");
        }
    }

    private String getError(String message) {
        JSONObject ret = new JSONObject();
        ret.put("error", 1);
        ret.put("url", message);
        return ret.toJSONString();
    }

    public List<String> upload_multi_file(String saveRootPath, String filePath, Function<String, String> nameFunc, StandardMultipartHttpServletRequest freq) {
        StopWatch stopWatch = new StopWatch("upfile");
        stopWatch.start("save file");

        String saveUrl = "/" + filePath;
        String realpath = saveRootPath + filePath;
        File dir = new File(realpath);
        System.out.println("exists = "+dir.exists());
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //String file_url[] = new String[1];
        List<String> urlList = new ArrayList<>();
        try {
            freq.getMultiFileMap().values().stream().forEach(files -> {
                files.stream().forEach((MultipartFile file) -> {
                    try {
                        String fileName = file.getOriginalFilename();
                        if (AppUtils.isBlank(fileName)) {
                            System.out.println("upload failed because of nofiles fileName=" + fileName);
                            return;
                        }
                        String _new_file_original_name = fileName;
                        if (null != nameFunc) {
                            _new_file_original_name = nameFunc.apply(fileName);
                        } else {
                            _new_file_original_name = fileName;
                        }
                        File newFile = new File(dir, _new_file_original_name);
                        file.transferTo(newFile);
                        //file_url[0] = saveUrl + newFile.getName();
                        urlList.add(FileConfigUtils.getImagesServerUrl()+saveUrl + newFile.getName());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            });
        } catch (Exception e2) {
            e2.printStackTrace();
            return urlList;
        }
        stopWatch.stop();
        return urlList;
    }
}

 

 

推荐阅读