[英]File upload in chunks via http post in java on android
我被要求使用http post發送文件。 該文件應以1 mb的塊發送。 我瀏覽了這段代碼IntentService以上傳文件 ,看起來我可以使用它了。 但是,我必須提供要在URL中發送的塊的起始字節作為參數。 因此,我不確定如何實現它。 我應該使用新的URL為每個塊實例化一個新的連接嗎? 還是我可以使用stream方法並以某種方式在將塊寫入輸出流之前更改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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.