• jquery+ spring+java 多文件上传


    描述:支持选择多个文件,目前限制最多上传5个文件

    一、前端代码

    1、html页面

     <form id="fm" method="post" action="" enctype="multipart/form-data">
                        <div class="form-group">
                            <label >请选择上传文件</label>
                            <div class="col-lg-10">
                                <input id="addFile"  name="addFile" class="form-control" class="filepath" type="file"  multiple="multiple" accept="application/msword,application/vnd.ms-works,text/plain,application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.wordprocessingml.document"><br>
                            </div>
                        </div>
                    </form>

    2、js代码

      add: function () {var files = document.getElementById("addFile").files;
            var number = files.length;
            if (number <=0) {
                toastr.error('请选择文件');
                return false;
            }
            if (number > 5) {
                toastr.error('上传文件个数不能超过5个');
                return false;
            }
            // 创建form对象
            var param = new FormData();
            // 循环将对应的文件放在form中
            for(var i = 0; i < files.length; i++){
                param.append("file"+i, files[i]);
            }// 上传需要将对应的文件类型上传的数据库
            param.append('fileType', fileType);
            // 文件个数,后台获取不到
            param.append('number', number);
            $.ajax({
                cache: false,
                type: "POST",
                url: backbasePath + '/apia/v1/knowledgeManager/uploadFile',
                data: param,
                async: true,
                contentType: false,
                processData: false,
                success: function (data) {
                    data = eval("(" + data + ")");
                    if ('000000' == data.code) {
                        toastr.success(data.msg);
                        //上传成功之后清楚掉之前选择的文件
                        $("#addFile").val("");
                        // 上传成功之后进行table的重新加载
                        $('#filesList').DataTable().ajax.reload();
                    } else if ('900000' == data.code) {
                        toastr.error('上传失败!');
                    } else {
                        toastr.error(data.msg);
                    }
                    $("#upload").modal('hide');
                },
                error: function () {
                    toastr.error('上传失败!');
                    $("#upload").modal('hide');
                }
            });
        }
       

    二、后端  /*     * 多文件上传     * @param request 请求

         * @param token   token
         * @param fileType 文件类型
         * @param number   上传文件个数
         * @return
         */
        @RequestMapping("/uploadFile")
        public Object upload(HttpServletRequest request,  @RequestParam(required = true) String fileType,
        @RequestParam(required = true) Integer number) { String result = null; // 用来处理多文件上传的请求类 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 用来存储文件列表 List<MultipartFile> templatesList = new ArrayList<>(); // 文件请求中获取的文件是集合类型 for (int i = 0 ; i < number ; i++) { templatesList.addAll(multipartRequest.getFiles("file" + i)); } // 将集合转换成数组 MultipartFile[] files = new MultipartFile[number]; templatesList.toArray(files); log.info("files"+files.length); if (files!=null && files.length > 0) {
    String path = filePath; path = path + "coalminehwaui/upload/";//定义位绝对路径 File parent = new File(new File(path).getAbsolutePath()); // 保存时间 Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); List<Map<String, Object>> dataList = new ArrayList<>(); System.out.println(" parent=" + parent); if (!parent.exists()) { parent.mkdirs(); } for(MultipartFile file :files){ // 文件信息 Map<String, Object> m = new HashMap<String, Object>(); try { // 检查文件大小 long fileSize = file.getSize(); if (fileSize > 1 * 1024 * 1024) { //return RequestResponseTool.getJsonMessage(RespCode.repeat, "上传失败!上传的文件大小超出了1M限制!"); return null; } // 检查文件MIME类型 String contentType = file.getContentType(); List<String> types = new ArrayList<String>(); //扩展名 doc dot types.add("application/msword"); //扩展名 docx types.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); //扩展名 pdf types.add("application/pdf"); //扩展名 txt types.add("text/plain"); //扩展名 wps types.add("application/vnd.ms-works"); //扩展名 xla xlc xlm xls xlt xlw types.add("application/vnd.ms-excel"); if (!types.contains(contentType)) { //return RequestResponseTool.getJsonMessage(RespCode.repeat, "上传失败!不允许上传此类型的文件!"); return null; } // 获取原始文件名 String originalFilename = file.getOriginalFilename(); // 根据文件名称进行查询,如果存在则更新否则新增 Map<String, Object> fileMap = knowledgeService.getFileByName(originalFilename,fileType); // 如果能查询出对应的数据,则进行更新操作 if(fileMap !=null && fileMap.size() >0){ String id =fileMap.get("id").toString(); String oldfileName =fileMap.get("file_name").toString(); // 找到之前的文件,如果存在则删除 File oldFile = new File( path+"/"+oldfileName); if (oldFile.exists()) { oldFile.delete(); } // 保存当前的文件 file.transferTo(new File(parent, oldfileName)); // 更新文件表中的大小 m.put("id", id); m.put("file_size", fileSize); m.put("style","update"); } // 如果查不到数据,则进行新增操作 else { // 新文件名称 String filename = UUID.randomUUID().toString(); String suffix = ""; int beginIndex = originalFilename.lastIndexOf("."); if (beginIndex != -1) { suffix = originalFilename.substring(beginIndex); } // 执行保存文件 file.transferTo(new File(parent, filename + suffix)); // 存放的文件路径 String file_path = "/upload/" + filename + suffix; //知识资源库id String knowledgeId = IDCode.knowledgeId + IDTool.getWebUserId() + ""; //文件表Id String file_id = IDCode.fileId + IDTool.getWebUserId() + ""; //文件逻辑名称(和路径中的名称保持一致) String file_name = filename + suffix; m.put("id", knowledgeId); m.put("type_id", fileType); m.put("file_id", file_id);// 创建时间 m.put("create_time", dateFormat.format(date)); // 创建id m.put("creater_id", opuid); m.put("file_name", file_name); m.put("file_real_name", originalFilename); m.put("file_path", file_path); m.put("file_size", fileSize); m.put("style","add"); } } catch (Exception ex) { ex.printStackTrace(); } // 将形成的数据放在集合中 dataList.add(m); } result = knowledgeService.add(dataList); } return result; }
  • 相关阅读:
    C++中new申请动态数组
    iOS 9之3D Touch功能
    在xcode找不到发布证书
    iOS 企业版 打包
    iOS证书详解--转载
    Failed to load the JNI shared library jvm.dl
    Xcode7.3打包ipa文件 报错和解决
    更新mac系统和更新到Xcode7.3版本出现的: cannot create __weak reference in file using manual reference counting
    Sun jdk, Openjdk, Icedtea jdk关系
    terminal color
  • 原文地址:https://www.cnblogs.com/flyShare/p/12516898.html
Copyright © 2020-2023  润新知