java大文件断点续传

作者: aishenla | 来源:发表于2018-07-24 14:51 被阅读304次

上传大文件经常遇到上传一半由于网络或者其他一些原因上传失败。然后又得重新上传(很麻烦),所以就想能不能做个断点上传的功能。于是网上搜索,发现市面上很少有断点上传的案例,有找到一个案例也是采用SOCKET作为上传方式(大文件上传,不适合使用POST,GET形式)。由于大文件夹不适合http上传的方式,所以就想能不能把大文件切割成n块小文件,然后上传这些小文件,所有小文件全部上传成功后再在服务器上进行拼接。这样不就可以实现断点上传,又解决了http不适合上传大文件的难题了吗!!!

服务端:
需要写两个接口
接口一:根据上传文件名称filename 判断是否之前上传过,没有则返回客户端chunck=1,有则读取记录chunck并返回。

接口二:上传文件,如果上传块数chunck=chuncks,遍历所有块文件拼接成一个完整文件。

接口一代码如下:

@WebServlet(urlPatterns = { "/ckeckFileServlet" })
public class CkeckFileServlet extends HttpServlet {

    private FileUploadStatusServiceI statusService;
    String repositoryPath;
    String uploadPath;

    @Override
    public void init(ServletConfig config) throws ServletException {
        ServletContext servletContext = config.getServletContext();
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        statusService = (FileUploadStatusServiceI) context.getBean("fileUploadStatusServiceImpl");

        repositoryPath = FileUtils.getTempDirectoryPath();
        uploadPath = config.getServletContext().getRealPath("datas/uploader");
        File up = new File(uploadPath);
        if (!up.exists()) {
            up.mkdir();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub

        String fileName = new String(req.getParameter("filename"));
        //String chunk = req.getParameter("chunk");
        //System.out.println(chunk);
        System.out.println(fileName);
        resp.setContentType("text/json; charset=utf-8");

        TfileUploadStatus file = statusService.get(fileName);

        try {
            if (file != null) {
                int schunk = file.getChunk();
                deleteFile(uploadPath + schunk + "_" + fileName);
                //long off = schunk * Long.parseLong(chunkSize);
                resp.getWriter().write("{\"off\":" + schunk + "}");

            } else {
                resp.getWriter().write("{\"off\":1}");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
} 

接口二代码如下:

@WebServlet(urlPatterns = { "/uploaderWithContinuinglyTransferring" })
public class UploaderServletWithContinuinglyTransferring extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private FileUploadStatusServiceI statusService;
    String repositoryPath;
    String uploadPath;

    @Override
    public void init(ServletConfig config) throws ServletException {
        ServletContext servletContext = config.getServletContext();
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        statusService = (FileUploadStatusServiceI) context.getBean("fileUploadStatusServiceImpl");

        repositoryPath = FileUtils.getTempDirectoryPath();
        System.out.println("临时目录:" + repositoryPath);
        uploadPath = config.getServletContext().getRealPath("datas/uploader");
        System.out.println("目录:" + uploadPath);
        File up = new File(uploadPath);
        if (!up.exists()) {
            up.mkdir();
        }
    }

    @SuppressWarnings("unchecked")
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        Integer schunk = null;// 分割块数
        Integer schunks = null;// 总分割数
        String name = null;// 文件名
        BufferedOutputStream outputStream = null;
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setSizeThreshold(1024);
                factory.setRepository(new File(repositoryPath));// 设置临时目录
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setHeaderEncoding("UTF-8");
                upload.setSizeMax(5 * 1024 * 1024 * 1024);// 设置附近大小
                List<FileItem> items = upload.parseRequest(request);
                // 生成新文件名

                String newFileName = null; 
                for (FileItem item : items) {
                    if (!item.isFormField()) {// 如果是文件类型
                        name = newFileName;// 获得文件名
                        if (name != null) {
                            String nFname = newFileName;
                            if (schunk != null) {
                                nFname = schunk + "_" + name;
                            }
                            File savedFile = new File(uploadPath, nFname);
                            item.write(savedFile);
                        }
                    } else {
                        // 判断是否带分割信息
                        if (item.getFieldName().equals("chunk")) {
                            schunk = Integer.parseInt(item.getString());
                            //System.out.println(schunk);
                        }
                        if (item.getFieldName().equals("chunks")) {
                            schunks = Integer.parseInt(item.getString());
                        }

                        if (item.getFieldName().equals("name")) {
                            newFileName = new String(item.getString());

                        }

                    }

                }
                //System.out.println(schunk + "/" + schunks);
                if (schunk != null && schunk == 1) {
                    TfileUploadStatus file = statusService.get(newFileName);
                    if (file != null) {
                        statusService.updateChunk(newFileName, schunk);
                    } else {
                        statusService.add(newFileName, schunk, schunks);
                    }

                } else {
                    TfileUploadStatus file = statusService.get(newFileName);
                    if (file != null) {
                        statusService.updateChunk(newFileName, schunk);
                    }
                }
                if (schunk != null && schunk.intValue() == schunks.intValue()) {
                    outputStream = new BufferedOutputStream(new FileOutputStream(new File(uploadPath, newFileName)));
                    // 遍历文件合并
                    for (int i = 1; i <= schunks; i++) {
                        //System.out.println("文件合并:" + i + "/" + schunks);
                        File tempFile = new File(uploadPath, i + "_" + name);
                        byte[] bytes = FileUtils.readFileToByteArray(tempFile);
                        outputStream.write(bytes);
                        outputStream.flush();
                        tempFile.delete();
                    }
                    outputStream.flush();
                }
                response.getWriter().write("{\"status\":true,\"newName\":\"" + newFileName + "\"}");
            } catch (FileUploadException e) {
                e.printStackTrace();
                response.getWriter().write("{\"status\":false}");
            } catch (Exception e) {
                e.printStackTrace();
                response.getWriter().write("{\"status\":false}");
            } finally {
                try {
                    if (outputStream != null)
                        outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

关键点:
1 需要与数据库交互,数据库存放文件名,第几块,总共几块这几个字段
2 上传时先调用接口一,通过文件名查询数据,如果有数据,则表示接下来要续传,接着调用第二个接口进行上传剩下的文件块
3 如果没有数据则表示是新文件上传,调用接口二,从第一块开始上传,接口二主要作用记录并更新文件的上传信息(数据库数据),在满足当前上传区块等于总块数时进行合并文件。

另外数据库新建表可以执行如下数据库语句
DROP TABLE IF EXISTS sys_file_upload_status;
CREATE TABLE sys_file_upload_status (
obj_id varchar(36) NOT NULL,
file_name varchar(1000) DEFAULT NULL,
chunk int(11) DEFAULT NULL,
chunks int(11) DEFAULT NULL,
PRIMARY KEY (obj_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

数据库交互大家使用自己熟悉的方式即可,比如jdbc,hibernate,mybatis等等,哪个好用用哪个。

相关文章

  • java大文件断点续传

    上传大文件经常遇到上传一半由于网络或者其他一些原因上传失败。然后又得重新上传(很麻烦),所以就想能不能做个断点上传...

  • IOS 断点续传原理浅析(第一篇)

    断点续传概述: 断点续传就是从文件上次中断的地方开始重新下载或上传数据,当下载大文件的时候,如果没有实现断点续传功...

  • iOS-16 断点续传 下载

    断点续传概述: 断点续传就是从文件上次中断的地方开始重新下载或上传数据,当下载大文件的时候,如果没有实现断点续传功...

  • 大文件断点续传

    对于大文件,往往需要通过断点续传来应对不稳定的网络环境。这几天正好做毕设,记下来断点续传的一些想法 H5断点续传 ...

  • 日常出现疑难问题

    BCompare4注册码 webuploader 大文件分片,断点续传,以及秒传功能 VMware Worksta...

  • 有关文件上传(未完待续)

    分片:将一个完整的大文件按照一定的规则切分成多个小的片段,方便后续的并发处理和断点续传。断点续传:当因为环境因素,...

  • vue-simple-uploader组件的一些使用心得

    前言 因为项目需要上传大文件,考虑使用分片上传、断点续传这些功能故选用vue-simple-uploader,期间...

  • Linux_285_Rsync断点续传

    rsync支持大文件断点续传rsync提供了如下的参数--partial默认情况下,rsync传输中断后,将会删除...

  • 大文件断点续传

    spark-MD5 增量计算切片 npm i spark-md5https://github.com/satazo...

  • Java http大文件断点续传上传

    1,项目调研 因为需要研究下断点上传的问题。找了很久终于找到一个比较好的项目。 在GoogleCode上面,代码弄...

网友评论

    本文标题:java大文件断点续传

    本文链接:https://www.haomeiwen.com/subject/ygnemftx.html