专栏名称: 安卓开发精选
伯乐在线旗下账号,分享安卓应用相关内容,包括:安卓应用开发、设计和动态等。
目录
相关文章推荐
51好读  ›  专栏  ›  安卓开发精选

Android 大文件上传秒传之实战篇(下)

安卓开发精选  · 公众号  · android  · 2016-11-26 14:13

正文

(点击 上方公众号 ,可快速关注)


来源:伯乐在线专栏作者 - Code4Android

链接:http://android.jobbole.com/85205/

点击 → 了解如何加入专栏作者


接上文


自定义FileBody


/**

* Created by xiehui on 2016/10/13.

*/

public class CustomFileBody extends AbstractContentBody {

private File file = null ;

private int chunk = 0 ; //第几个分片

private int chunks = 1 ; //总分片数

private int chunkLength = 1024 * 1024 * 1 ; //分片大小1MB

public CustomFileBody ( File file ) {

this ( file , "application/octet-stream" );

}

public CustomFileBody ( ChunkInfo chunkInfo ) {

this ( new File ( chunkInfo . getFilePath ()), "application/octet-stream" );

this . chunk = chunkInfo . getChunk ();

this . chunks = chunkInfo . getChunks ();

this . file = new File ( chunkInfo . getFilePath ());

if ( this . chunk == this . chunks ) {

//先不判断,固定1M

//this.chunkLength=this.file.length()-(this)

}

}

public CustomFileBody ( File file , String mimeType ) {

super ( mimeType );

if ( file == null ) {

throw new IllegalArgumentException ( "File may not be null" );

} else {

this . file = file ;

}

}

@Override

public String getFilename () {

return this . file . getName ();

}

@Override

public String getCharset () {

return null ;

}

public InputStream getInputStream () throws IOException {

return new FileInputStream ( this . file );

}

@Override

public String getTransferEncoding () {

return "binary" ;

}

@Override

public long getContentLength () {

return chunkLength ;

}

@Override

public void writeTo ( OutputStream out ) throws IOException {

if ( out == null ) {

throw new IllegalArgumentException ( "Output stream may not be null" );

} else {

//不使用FileInputStream

RandomAccessFile randomAccessFile = new RandomAccessFile ( this . file , "r" );

try {

//int size = 1024 * 1;//1KB缓冲区读取数据

byte [] tmp = new byte [ 1024 ];

//randomAccessFile.seek(chunk * chunkLength);

if ( chunk + 1 chunks ){ //中间分片

randomAccessFile . seek ( chunk * chunkLength );

int n = 0 ;

long readLength = 0 ; //记录已读字节数

while ( readLength chunkLength - 1024 ) {

n = randomAccessFile . read ( tmp , 0 , 1024 );

readLength += 1024 ;

out . write ( tmp , 0 , n );

}

if ( readLength chunkLength ) {

n = randomAccessFile . read ( tmp , 0 , ( int )( chunkLength - readLength ));

out . write ( tmp , 0 , n );

}

} else {

randomAccessFile . seek ( chunk * chunkLength );

int n = 0 ;

while (( n = randomAccessFile . read ( tmp , 0 , 1024 )) != - 1 ) {

out . write ( tmp , 0 , n );

}

}

out . flush ();

} finally {

randomAccessFile . close ();

}

}

}

public File getFile () {

return this . file ;

}

}


文件分块上传模型类ChunkInfo


/ * Created by xiehui on 2016 / 10 / 21.

*/

public class ChunkInfo extends FileInfo implements Serializable {

/**







请到「今天看啥」查看全文