Mikhail Kim
Mikhail Kim

Reputation: 589

File upload in chunks via http post in java on android

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 ?

Upvotes: 4

Views: 7419

Answers (2)

Muthu
Muthu

Reputation: 1022

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);
    }

Upvotes: 2

user207421
user207421

Reputation: 310875

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.

Upvotes: 3

Related Questions