iOS large file multipart upload and breakpoint continuation

Source: Internet
Author: User

Summarize the problem of large file multipart upload and breakpoint continuation. Because the file is too large (such as 1G or more), you must consider the upload process network interruption. HTTP network request itself already has the multipart upload function, when the transmission of the file is relatively large, the HTTP protocol will automatically slice the file (block), but this is not the focus we now say, we have to do is to ensure that the network after the interruption of the 1G files uploaded in the next network connection should not be re-transmitted. So we are in the local upload, the large files to be fragmented, such as divided into 1024*1024b, the large file is divided into 1M pieces for uploading, the server after receiving, and then merge these slices into the original file, this is the basic principle of sharding. The continuation of the breakpoint requires the local to record the status of each piece of upload, I have three states marked (wait loading finish), when the network is interrupted, once again connected, upload from the breakpoint. The server determines whether the file has been fully uploaded by file name and total number of slices.

Here's the details:

1, first get the file (audio and video, pictures)

In two cases, one is taken directly from the album Library, and one is called the camera. If it is obtained through Uiimagepickerview (details not detailed, a lot of online), we will find that when you select a video, you will see a compressed page of Figure 1, and finally our app gets the video is this compressed video (not the original video in the video library, Here is a point of attention, after the operation of the compressed video, remember to release, the system will not help you release, you need to manually operate, the following will say), and then through the Uiimagepickerview protocol method of-(void) Imagepickercontroller: (uiimagepickercontroller *) Picker Didfinishpickingmediawithinfo: (NSDictionary *) info get info for video

FileInfo = {

Uiimagepickercontrollermediatype = "";

Uiimagepickercontrollermediaurl = "file:///private/var/mobile/Containers/Data/Application/ 2aae9e44-0e6d-4499-9ac3-93d44d8342ea/tmp/trim. F36ec46c-4219-43c8-96a7-fa7141ab64d2. MOV ";

Uiimagepickercontrollerreferenceurl = "Assets-library://asset/asset. Mov?id=deda9406-3223-4f87-abb2-98fb5f5eb9c4&ext=mov ";


Uiimagepickercontrollermediatype is the type of the selected file, such as Kuttypeimage,kuttypemovie. Note here the difference between movie and video, a video file with sound, a video file without sound, and of course audio is the only voice without video. Uiimagepickercontrollermediaurl is the URL of the video (if it is taken by the camera, then this is the original shot of the video, if it is selected in the album Library, that is the video generated after compression), note that this URL does not point to the album Library, Through this URL you can manipulate this video such as delete, copy, etc., can get the size of compressed video. Uiimagepickercontrollerreferenceurl is a URL to the album, and the official explanation is an nsurl that references a asset in the Assetslibrary framework, Through this URL, you can get all the information of the video, including file name, thumbnail, length, etc. (via alassetslibrary assetslibrary assetforurl: Referenceurl resultblock:).

If the camera is taken, note two ways to save: Picture saved to album assetslibrary writeimagedatatosavedphotosalbum: UIImageJPEGRepresentation([info valueforkey: Uiimagepickercontrolleroriginalimage], (cgfloat)1.0 ) metadata:nil completionblock: failureblock:

Methods of high Fidelity compressed pictures NSData * UIImageJPEGRepresentation (UIImage *image, CGFloat compressionquality)

Video saved to album:assetslibrary writevideoatpathtosavedphotosalbum:mediaurl completionblock:failureblock:

Here, we get all the required files and file information. The next thing to do is to fragment the file.

2. Shard of files to be acquired

First, I'll save the retrieved file in a class like this

@interface cnfile: nsobject

@property (nonatomic,copy) nsstring* filetype;//image or movie

@property (nonatomic,copy) nsstring* filePath; files in the app path

@property (nonatomic,copy) nsstring* fileName; file name

@property (nonatomic,assign) nsinteger fileSize; File size

@property (nonatomic,assign) nsinteger trunks; total number of pieces

@property (nonatomic,copy) nsstring* fileInfo;

@property (nonatomic,strong) UIImage* fileimage; file thumbnail image

@property (nonatomic,strong) nsmutablearray* Filearr; mark the upload status of each piece


This allows us to operate on each of the Cnfile objects.

-(void) Readdatawithchunk: (nsinteger) chunk file: (cnfile*) file{

How to obtain the total number of slices:

int offset = 1024x768*1024x768(size of each piece is 1M)

Nsinteger chunks = (file. FileSize%=0)? ( (int) (file. FileSize/1024x768)):((int) (file. FileSize/(1024x768*1024x768) + 1));

NSLog(@ "chunks =%ld", (long) chunks);

Shard the file and read the data for each slice:

NSData* data;

Nsfilehandle *readhandle = [nsfilehandle filehandleforreadingatpath:file. FilePath];

[Readhandle seektofileoffset: Offset * chunk];

data = [Readhandle readdataoflength: offset];


So we get each piece of data to upload, and then ask the server, whether the film already exists

(Method-(void) Ifhavedata: (nsdata*) data withchunk: (nsinteger) chunk file: (cnfile*) File)

, if present, make chunk+1, repeat the method above to read the next piece, until the server does not exist, then upload the piece of data. Note In this method that you set the upload status of the chunk (wait loading finish), which is related to the local determination that the file has all been uploaded.

The next step is the upload process:

-(void) Uploaddata: (nsdata*) data withchunk: (nsinteger) chunk file: (cnfile* ) file;

After the server returns the upload success, we have to do a lot of things:

1) First the flag of the film has been successfully uploaded

[File. Filearr replaceobjectatindex:chunk withobject:@ "Finish"];

2) to see if all of the pieces of flag have been set to finish, if it has been finishi, indicating that the file upload completed, then delete the file, upload the next file or end.

For (nsinteger j = 0; j<chunks; j + +) {

If (j = = Chunks | | ((j = = chunks- 1) && ([File. Filearr[j] isequaltostring:@ "Finish"] ))

[Me deletefile: file. FilePath];

[Me readnextfile];


3) If not all finish, then see if the local next chunk flag is wait

NSLog(@ " View the status of%ld slices ", chunk+1);

For(nsinteger i = chunk+1; i < chunks;i++)


NSString* flag = [file. Filearr objectatindex: i];

If ([flag isequaltostring:@ "Wait"]) {

[Me readdatawithchunk: I filename: filename file: file];




Between the 2nd and 3 steps can have a 2.5) to determine whether to suspend the upload

If(me.ispause = = YES)


will now read the first few pieces of the document saved to a local

[self saveprogresswithchunk:chunk file:file];

return ;


This operation is actually the same as the upload process interrupt network, in order to continue the transmission of the breakpoint, in the disconnection or pause, we have to save the current progress, so that the next upload to skip the previous set of finish.

Then there is a problem, if we just such a linear piece of the upload, actually lost the meaning of the multipart upload, it should be combined with multi-threading, so that the multipart upload process concurrent execution, while uploading multiple pieces, thus improving the efficiency of uploading, and make full use of the network bandwidth.

Dispatch_async (dispatch_queue_t queue, ^{

[Me readdatawithchunk: chunk];


Finally, after each upload of a video, go to the settings to see if your app occupies more storage space, oh, if you do not process the generated compressed video, you will find that your app's space consumption is very large.

Transferred from:

iOS large file multipart upload and breakpoint continuation

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.