我被要求使用http post发送文件。该文件应以1 mb的块发送。我查看了这段代码IntentService to upload a file,看起来我可以在我的情况下使用它。但是,我必须提供我在URL中发送的块的起始字节作为参数。因此,我不知道如何实现它。我应该使用新网址为每个块实例化一个新连接吗?或者我可以使用流方法,并在将块写入输出流之前以某种方式更改URL?
答案 0 :(得分:2)
只需使用URL
和HttpURLConnection
,然后使用所需的块大小调用setChunkedTransferMode()
。
您不需要设置起始字节,除非您还没有告诉我们。
答案 1 :(得分:1)
这可以通过使用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);
}