android java 中通过 http post 分块上传文件
File upload in chunks via http post in java on android
我被要求使用 http post 发送文件。该文件应以 1 mb 的块发送。我查看了这段代码 IntentService to upload a file,看起来我可以在我的案例中使用它。但是,我必须提供我在 URL 中发送的块的起始字节作为参数。因此我不确定如何完成它。我应该用新的 url 为每个块实例化一个新连接吗?或者我可以使用流方法并在将块写入输出流之前以某种方式更改 url 吗?
这可以通过使用 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);
}
只需使用 URL
和 HttpURLConnection
并使用所需的块大小调用 setChunkedTransferMode()
。
你不需要设置起始字节,除非有什么你没有告诉我们的。
我被要求使用 http post 发送文件。该文件应以 1 mb 的块发送。我查看了这段代码 IntentService to upload a file,看起来我可以在我的案例中使用它。但是,我必须提供我在 URL 中发送的块的起始字节作为参数。因此我不确定如何完成它。我应该用新的 url 为每个块实例化一个新连接吗?或者我可以使用流方法并在将块写入输出流之前以某种方式更改 url 吗?
这可以通过使用 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);
}
只需使用 URL
和 HttpURLConnection
并使用所需的块大小调用 setChunkedTransferMode()
。
你不需要设置起始字节,除非有什么你没有告诉我们的。