我被要求使用HTTP POST发送文件。每个文件应该分成1MB的块进行发送。我查看了这段代码 IntentService上传文件,看起来我可以在我的情况下使用它。但是,我必须在URL中作为参数提供我发送的块的起始字节。因此,我不确定如何完成它。我应该为每个块实例化一个新连接并使用新的URL吗?还是我可以使用流方法,在块写入输出流之前以某种方式更改URL?
只需使用URL
和HttpURLConnection
,并调用setChunkedTransferMode()
函数,并设置所需的块大小。
除非您有未告诉我们的情况,否则不需要设置起始字节。
可以使用MultipartEntity来完成此操作。以下代码将帮助您理解。
final int cSize = 1024 * 1024; // size of chunk
File file = new File("path to file");
final long pieces = file.length()/cSize // used to return file length.
HttpPost request = new HttpPost(endpoint);
BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file));
for (int i= 0; i< pieces; i++) {
byte[] buffer = new byte[cSize];
if(stream.read(buffer) ==-1)
break;
MultipartEntity entity = new MultipartEntity();
entity.addPart("chunk_id", new StringBody(String.valueOf(i))); //Chunk Id used for identification.
request.setEntity(entity);
ByteArrayInputStream arrayStream = new ByteArrayInputStream(buffer);
entity.addPart("file_data", new InputStreamBody(arrayStream, filename));
HttpClient client = app.getHttpClient();
client.execute(request);
}
pieces = file.length()
应改为 pieces=file.length()/cSize;
。stream.skip(i* cSize);
这条语句应该被移除。valueOf(id)
更好的写法是 valueOf(i);
。 - greenappsstream.read(buffer);
你应该检查返回值。pieces
不会包括文件的最后一部分,因此会丢失。 - greenapps