I am asked to send a file using http post. The file should be sent in chunks of 1 mb. I looked through this code IntentService to upload a file and it looks like I could use it in my case. However, I have to supply the starting byte of the chunk I am sending in URL as a parameter. Thus I am not sure how to accomplish it. Should I instantiate a new connection for every chunk with the new url? Or can I use the stream method and somehow change the url before the chunk is written to the outputstream ?
2 Answers
Just use URL and HttpURLConnection and call setChunkedTransferMode() with the desired chunk size.
You don't need to set the start byte, unless there is something you haven't told us.
2 Comments
Abhinav Saxena
How about if there is a crash due to connectivity, how will we resume from the last place where the crash occurred? I am talking about resume control.
user207421
Just set the appropriate header value on the
URLConnection, and seek to the same place in the input before you start transferring.This can be done by using MultipartEntity. Following code will help you understand.
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);
}
10 Comments
Muthu
@greenapps i have added some comments to code to make it more clear.
greenapps
pieces = file.length() that should be pieces=file.length()/cSize;. stream.skip(i* cSize);. That statement should be removed. valueOf(id). Better would be valueOf(i);.greenapps
stream.read(buffer); you should check the return value. pieces will not include the last piece of the file so that will go missing.greenapps
You are completely wrong. If pieces would be equal to file.length() the for loop would be executed file.length times. So more than several millon times. Is that what you want? You apparently never tested that code.
greenapps
My god. Why do i have to repeat things? All i said still comes true.
|