简体   繁体   中英

iOS: Uploading a ZIP file with AFNetworking

I have to upload a ZIP file to a server, I am using this code:

NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:methode parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"data.xml"];

        ZipArchive  *zip1 = [[ZipArchive alloc] init];
        BOOL ret = [zip1 CreateZipFile2:[documentsDirectory stringByAppendingPathComponent:@"data.zip"]];

        ret = [zip1 addFileToZip:databasePath newname:@"data.xml"];

        [formData appendPartWithFileData:[NSData dataWithContentsOfFile:[documentsDirectory stringByAppendingPathComponent:@"data.zip"]]
                                    name:@"FILE"
                                fileName:@"data.zip"
                                mimeType:@"application/zip"];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
 [operation start];

The ZIP file is fine. The request is fine. But the server response shows that the file was corrupted on its way. Instead of 931 bytes the server receives only a 855 bytes ZIP file.

The server admin told me (no iOS Experience) that I have to set the proper upload type (like in HTML the case would be):

enctype="multipart/form-data"

Shouldn't you close the handle to the zip file prior to trying to attach it to the request? You can't be sure it got written to storage completely otherwise, so you might get this behavior.

[zip1 CloseZipFile2];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM