File upload pause and resume in Android

2019-04-13 00:44发布

问题:

I have a android application.I want implement the function upload the image/video into server by thread or AsyncTasks.For uploading the image/video,I want implement the pause and resume function.That means it will must be maintain the pause and resume function when it will upload into server.Now i have query is it possible implement this funcation(pause and resume)?If have any idea about this then please help to me ,how i will maintain this.Thanks all.

回答1:

I believe you have done the normal uploads to the server. To implement a resumable upload you have to split the file into chunks and specify the byte range of file that is being send to server. I can give you a rough idea on this.

Eg: Suppose you have a 5 MB(million bytes) file. You have to send the file as follows.

Part 1: 0000000- 9999999 bytes -HTTP 204

Part 2: 1000000- 1999999 bytes -HTTP 204

Part 3: 2000000- 2999999 bytes -HTTP 204

Part 4: 3000000- 3999999 bytes -HTTP 204

Part 5: 4000000- 4999999 bytes -HTTP 200

Set the following headers

Content-Length: 1000000

Content-Range: bytes 1000000/5000000

You have to specify the content range and send the corresponding byte stream array. Unless a file is complete, all the successful chunk uploads will return a 204. In case you upload breaks at any point, you can poll the server and get the status of upload. Resuming can be done from that point of file to complete the chunk where it broke. We are splitting the file into chunks as we cannot hold the whole thing in memory. It is ok to send the whole file as one single part and resume at the exact byte point for smaller files.

Another option is to manage the index locally. On completion of every chunk, update the status of index variable to a file. If an upload is to be resumed you can resume the whole chunk from beginning. You don't have to poll server to get the status.

After a succesful complete upload, 200 status is returned by server(Even if you upload the whole file in a single chunk with the headers set). Please refer to the Youtube's documentation or Pandastream for more details.

https://developers.google.com/youtube/2.0/developers_guide_protocol_resumable_uploads