okhttpclient 文件断点上传

使用okhttpclient上传时,需要上传剩下一部分文件内容:


public class FileRequestBody extends RequestBody {

    private static final int SEGMENT_SIZE = 2048; // okio.Segment.SIZE

    private final InputStream inputStream;
    private final ProgressListener listener;
    private final String contentType;
    private long mBytesRead;

    public FileRequestBody (InputStream inputStream,String contentType,long lastCompletedBytes, ProgressListener listener) {
        this.inputStream = inputStream;
        this.contentType = contentType;
        this.listener = listener;
		this.mBytesRead = lastCompletedBytes;

    }

    @Override
    public long contentLength() {
 			try {
				return inputStream.available();
			}catch(Exception e){
				e.printStackTrace();
			}finally {
			}
			return 0;
    }

    @Override
    public MediaType contentType() {
        return MediaType.parse(contentType);
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        Source source = null;
        try {
            source = Okio.source(inputStream);
            long read;

			
            while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
                mBytesRead += read;
                sink.flush();
                this.listener.transferred(total);

            }
        } finally {
            Util.closeQuietly(source);
        }
    }

    public interface ProgressListener {
        void transferred(long num);
    }

}

使用:
Builder HttpRequestBuild =  new Request.Builder();
HttpRequestBuild.url(fileUploadUrl);//自己上传url
File localFile = new File("xxx/xxx/xxx.txt");//自己上传的文件名字
RandomAccessFile file = new RandomAccessFile(localFile, "r");
file.seek(size);// 仅上传未完成的文件内容
RequestBody fileBody = FileRequestBody(file.getFD(),"application/octet-stream",
,size,
new FileRequestBody.ProgressListener(){  @Override void transferred(long num){};} ); 
 
HttpRequestBuild.put(fileBody);
//服务器中的标签
HttpRequestBuild.addHeader(
                "UploadFileRange",
                String.valueOf(size) + "-"
                        + localFile.length() - 1 + "/*");
 
Request  request = HttpRequestBuild.build();
Response response = mHttpClient.newCall(request).execute();
//注意关掉流
file.close();


 

部分代码引用以下网址:

http://stackoverflow.com/questions/25962595/tracking-progress-of-multipart-file-upload-using-okhttp





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值