打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Java简单实现大文件分包上传服务器大致思路

     最近写一个大文件数据通过分包方式上传Web服务器小需求,文件数据按照文件分包后的先后顺序进行上报。大致流程:

1,文件准备上报请求

     1)客户端计算即将上传的文件的大小、crc校验码;

     2)发送文件信息到服务器,包括文件大小、校验码CRC,文件格式;

     3)Web服务端在接收到文件上传请求后,生成中心唯一fileId,同时以该fileId作为缓存主键,缓存文件信息。并在指定路径生成以fileId命名的临时文件。

     String  fileId= UUID.randomUUID().toString()。

    String parentPath = request.getServletContext().getRealPath("/")+"tempFile/";
   File file = new File(parentPath,fileName);   file.createNewFile();
4)Web服务器将该fileid做为请求响应,反馈给客户端。

2,文件数据上报请求

1),客户端将要上报文件按照一定大小进行分包。

2),客户端通过HTTP上传分包数据,消息头包括fileid,分包数据在整个文件的偏移量(offset)、分包数据的长度(dataLen),

分包数据的校验码(crc)以及分包数据消息体。

3),Web服务端在收到数据请求时,先判断该fileid缓存是否存在,如果存在该fileid缓存,读取请求的消息体数据,

先进行数据校验。校验成功,根据解析的fileid,打开在指定路径的临时文件,将消息体数据追加写入临时文件:

String filePath = request.getServletContext().getRealPath("/tempFile/");

File file = new File(filePath,fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file, true);

4),客户端和Web服务器重复第2、3步。判断已接收的分包数据总大小是否和文件大小一致。如果一致,表面文件已经接收完整,

计算接收完毕的文件crc校验码,和在请求阶段上传的总文件的CRC校验码进行比对。一致则该文件成功接收,否则删除该临时文件,

并通知客户端文件接收失败。

InputStream inputStream = request.getInputStream();byte buffer[] = new byte[content_length];int off_set=1;int totalRead=0;while (off_set>0){    off_set = inputStream.read(buffer,totalRead,buffer.length-totalRead);    if(off_set>-1)        totalRead=totalRead+off_set;}inputStream.close();

crc校验部分:

public String getCheckCrc(FileInputStream fileInputStream){    byte[] buffer = new byte[Length];    String result="";    CRC32 crc32 = new CRC32();    try {        if (fileInputStream != null) {            int read = 0;            while ((read = fileInputStream.read(buffer)) > 0) {                crc32.update(buffer,0,read);            }            fileInputStream.close();            result = String.valueOf(crc32.getValue());        }    }catch (Exception e){        logger.error("getCheckCrc:"+e.toString());    }    return result;}
public String getCheckCrcEx(byte[] temp){    String result="";    try{        byte[] buffer;        int count=temp.length/Length+1;        CRC32 crc32 = new CRC32();        int len=0;        for(int i=0;i<count;i++){            if(temp.length<Length){                len=temp.length;            }else{                if(i<count-1){                    len=Length;                }else{                    len=temp.length-i*Length;                }            }            buffer=new byte[len];            System.arraycopy(temp,i*Length,buffer,0,len);            crc32.update(buffer,0,len);        }        result = String.valueOf(crc32.getValue());    }catch (Exception e){        logger.error("getCheckCrcEx:"+e.toString());    }    return result;}



本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
关于C#对文件的压缩和解压缩的问题
.net 压缩文件夹
Asp.net中文件的压缩与解压
【新提醒】Unity 游戏资源更新
TcpClient接收数据不全
C# 计算文件的 Hash 值
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服