java webuploader断续上传代码

分片接口

 /**
     * 上传文档分片测试    //前端页面上传文件夹按钮调用的方法
     *
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @Doc("上传文档")
    @POST("/uploadTest")
    public ApiResponse uploadTest(Request request) throws Exception {
        this.logMethodCalled("uploadDocument");

        HttpServletRequest servletRequest = request.getServletRequest();
        //CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        // MultipartHttpServletRequest multiReq = multipartResolver.re(request);
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //集合,每一个FileItem对应一个Form表单的输入项
        List list = upload.parseRequest(servletRequest);
        long start = System.currentTimeMillis();

        String chunk = "0";
        String fileMd5 = "";
        for (FileItem item : list) {
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName.equals("md5")) {
                    fileMd5 = item.getString("utf-8");
                    System.out.println(fileMd5);
                }
                if (fieldName.equals("chunk")) {
                    chunk = item.getString("utf-8");
                    System.out.println("当前分片数:" + chunk);
                }
                if (fieldName.equals("chunks")) {
                    String chunks = item.getString("utf-8");
                    System.out.println("总分片数:" + chunks);
                }

            } else {
                String filename = item.getName();
                if (filename == null || filename.trim().equals("")) {
                    continue;
                }
                // File chunkFile = new File("D:\\tmp\\22\\" + fileMd5+File.separator+chunk);
                //FileUtils.copyInputStreamToFile(item.getInputStream(), chunkFile);
                //获取item输入流
                InputStream inputStream = item.getInputStream();
                String uuid = ObjectHelper.getUUID();
                System.out.println(uuid);
                File file = new File("D:\\tmp\\22\\" + fileMd5 + File.separator + chunk);
                if (!file.exists()) {
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }

                //创建一个文件输出流
                RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

                //创建一个缓冲区
                byte[] bff = new byte[5 * 1024 * 1024];
                //判断输入流是否已经读完的标识
                int len = 0;
                while ((len = inputStream.read(bff)) != -1) {
                    //System.out.println(len);
                    //fileOutputStream.write(len);
                    randomAccessFile.write(bff, 0, len);
                }
                inputStream.close();
                randomAccessFile.close();

                String path1 = System.getProperty("catalina.home") + File.separator + "temp";
                System.out.println("临时路径22222=====" + path1);
                File dir = new File(path1);
                File[] files = dir.listFiles();
                for (File tempfile : files) {
                    System.out.println(file + ":" + tempfile.delete());
                }
                //获取item输入流
                //创建一个文件输出流
                // FileOutputStream fileOutputStream  =new FileOutputStream(savePath+"\\"+filename);
                //创建一个缓冲区
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("花费上传时间:" + (endTime - start) + "ms");
        return ApiResponse.ok("上传成功");
    }

 
 

检查分片


    /**
     * 检查分片
     *
     * @param fileMd5
     */
    @GET("checkshard")
    public ApiResponse searchFileByMd5(String fileMd5) {
        Result result = new Result();
        // 读取目录里的所有文件
        File dir = new File("D:\\tmp\\22\\" + fileMd5);
        File[] childs = dir.listFiles();
        if (childs == null) {
            result.setStatusCode(0);
        } else {
            result.setStatusCode(childs.length - 1);//文件上传中断过,返回当前已经上传到的下标
        }
        return ApiResponse.ok(result);

    }

合并


    /**
     * 合成分片
     *
     */
    @POST("MergeFiles")
    public ApiResponse MergeFiles(MultipartFileParam fileParam,String folderId) throws IOException {
        logMethodCalled("MergeFiles");
        logParamValue("fileParam", fileParam);
        Result result = new Result();
        result.setMessage("合并操作");
        String fileSufix = "";
        String fileName = fileParam.getName();
        //文件唯一标识
        String fileMd5 = fileParam.getMd5();

        //获取文件名后缀
        if (Strings.isNotEmpty(fileName) && fileName.contains(".")) {
            fileSufix = FileUtil.getFileSufix(fileName);
            fileSufix = "." + fileSufix;
        }else{
            return ApiResponse.badRequest("参数为空");
        }

        folderId = "224131721900199936";
        //获取路径地址,把合并的文件放在此位置
        ResultInfo resultInfo = dmFolderService.getDmFolderModel(folderId);

        if (resultInfo.getData() == null) {
            return ApiResponse.badRequest("目标文件夹不存在");
        }
        DmFolderModel dmFolderModel = (DmFolderModel) resultInfo.getData();
        //获取路径地址
        String absolutePath = dmFolderModel.getAbsolutePath();
        //然后拼接绝对地址
        String realPath = absolutePath + File.separator + ObjectHelper.getUUID() + fileSufix;
        String uploadFileRealPath = EpmFileUtils.getUploadFileRealPath();
        uploadFileRealPath = uploadFileRealPath + realPath;

        // 读取目录里的所有文件
        String path = "D:\\tmp\\22";
        path += File.separator + fileMd5;
        //获取文件夹下所有文件,并排序0-1-2-3-4
        File file = new File(path);
        File[] fileArray = file.listFiles(new FileFilter() {
            // 排除目录,只要文件
            @Override
            public boolean accept(File pathname) {
                if (pathname.isDirectory()) {
                    return false;
                }
                return true;
            }
        });

        // 转成集合,便于排序
        List fileList = new ArrayList(Arrays.asList(fileArray));
        // 从小到大排序
        Collections.sort(fileList, new Comparator() {

            @Override
            public int compare(File o1, File o2) {
                if (Integer.parseInt(o1.getName()) < Integer.parseInt(o2.getName())) {
                    return -1;
                }
                return 1;
            }

        });

        // 新建保存文件
        //File outputFile = new File(path + File.separator + UUID.randomUUID().toString() + fileSufix);
        File outputFile = new File(uploadFileRealPath);
        File parentFile = outputFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        // 创建文件
        outputFile.createNewFile();
        // 输出流
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        FileChannel outChannel = fileOutputStream.getChannel();
        // 合并
        FileChannel inChannel;
        for (File f : fileList) {
            inChannel = new FileInputStream(f).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
            inChannel.close();
        }
        // 关闭流
        fileOutputStream.close();
        outChannel.close();
        //删除临时文件
        if (file.exists()) {
            //放到得到当前文件夹下的目录数组
            File[] files = file.listFiles();
            //判断是否为空文件夹 如果是则直接删除文件夹
            if (null == files || files.length == 0) {
                file.delete();
            } else {
                //遍历数组
                for (File f : files) {
                    f.delete();
                }
                //经过递归已经删除所有子目录起文件夹 最后删除本身
                file.delete();
            }
        }

        return ApiResponse.ok(result);

    }

你可能感兴趣的:(java webuploader断续上传代码)