iOS upload multiple files

Posted by defeated on Wed, 11 Dec 2019 16:26:29 +0100

Upload file format

POST /php/upload/upload.php HTTP/1.1
Host: 127.0.0.1
 Content type: multipart / form data; boundary = identity (customizable)
Request body
 --Identity (customizable, but must be consistent with the request header)
Content-Disposition: form-data; name="userfile[]"; filename="head1.png"
Content-Type: image/png
 Blank line
 File binary data
 --Identity (customizable, but must be consistent with the request header)
Content-Disposition: form-data; name="userfile[]"; filename="head2.png"
Content-Type: image/png
 Blank line
 File binary data
 --Identity (customizable, but must be consistent with the request header)
Content disposition: form data; name = "field name"

Data value
 --Identity (customizable, but must be consistent with the request header)--

Multi file file upload


#define kBOUNDARY @"abc"
- (void)viewDidLoad {
    [super viewDidLoad];
    // Network link
    NSString *netUrl = @"http://127.0.0.1/php/upload/upload-m.php";
    
    // File path
    NSString *path1 = [[NSBundle mainBundle] pathForResource:@"head1.png" ofType:nil];
    NSString *path2 = [[NSBundle mainBundle] pathForResource:@"head2.png" ofType:nil];
    NSArray *array = @[path1, path2];
    
    // Field name
    NSString *fieldName = @"userfile[]";
    // data dictionary
    NSDictionary *dict = @{@"username":@"mazaiting"};
    // Upload files
    [self uploadFiles:netUrl fieldName:fieldName filePaths:array params:dict];
    
}

// Upload multiple files
// netUrl network link
// fieldName field name
// filePaths array of file paths
// params parameter dictionary
- (void)uploadFiles:(NSString *)netUrl fieldName:(NSString *)fieldName filePaths:(NSArray *)filePaths params:(NSDictionary *)params {
    NSURL *url = [NSURL URLWithString:netUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"post";
    // Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryJa8BALfIc9saou2X
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",kBOUNDARY] forHTTPHeaderField:@"Content-Type"];
    request.HTTPBody = [self body:fieldName filePaths:filePaths params:params];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:
     ^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
         if (connectionError) {
             NSLog(@"Connection error %@", connectionError);
             return;
         }
         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
         if (httpResponse.statusCode == 200 || httpResponse.statusCode == 304) {
             // Analytical data
             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
             NSLog(@"%@",dict);
         } else {
             NSLog(@"Server internal error");
         }
     }];
}

// Build request body
- (NSData *)body:(NSString *)fieldName filePaths:(NSArray *)filePaths params:(NSDictionary *)params {
    NSMutableData *mData = [NSMutableData data];
//    ------WebKitFormBoundaryJa8BALfIc9saou2X
//    Content-Disposition: form-data; name="userfile[]"; filename="head1.png"
//    Content-Type: image/png
//    
//    File binary data
//    ------WebKitFormBoundaryJa8BALfIc9saou2X
//    Content-Disposition: form-data; name="userfile[]"; filename="head2.png"
//    Content-Type: image/png
//    
//    File binary data
//    ------WebKitFormBoundaryJa8BALfIc9saou2X
//    Content-Disposition: form-data; name="username"
//    
//    mazaiting
//    ------WebKitFormBoundaryJa8BALfIc9saou2X--
    
    // Building files, traversing arrays
    [filePaths enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//              ------WebKitFormBoundaryJa8BALfIc9saou2X
//            Content-Disposition: form-data; name="userfile[]"; filename="head2.png"
//            Content-Type: image/png
//        
//            File binary data
        
        NSMutableString *mString = [NSMutableString string];
        // Determine whether it is the first file. If it is, you do not need to add "\ r\n"
        if (idx != 0) {
            [mString appendString:@"\r\n"];
        }
        [mString appendFormat:@"--%@\r\n", kBOUNDARY];
        [mString appendFormat:@"Content-Disposition: form-data; name=%@; filename=%@\r\n", fieldName, [obj lastPathComponent]];
        [mString appendString:@"Content-Type: application/octet-stream\r\n"];
        [mString appendString:@"\r\n"];
        [mData appendData:[mString dataUsingEncoding:NSUTF8StringEncoding]];
        // Binary data of splicing file
        NSData *data = [NSData dataWithContentsOfFile:obj];
        [mData appendData:data];
    }];
    
    // Building data
    //    ------WebKitFormBoundaryJa8BALfIc9saou2X
    //    Content-Disposition: form-data; name="username"
    //
    //    mazaiting
    //    ------WebKitFormBoundaryJa8BALfIc9saou2X--
    [params enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSMutableString *mString = [NSMutableString string];
        [mString appendFormat:@"\r\n--%@\r\n", kBOUNDARY];
        [mString appendFormat:@"Content-Disposition: form-data; name=%@\r\n", key];
        [mString appendString:@"\r\n"];
        [mString appendFormat:@"%@", obj];
        [mData appendData:[mString dataUsingEncoding:NSUTF8StringEncoding]];
    }];
    
    // End statement
    NSString *end = [NSString stringWithFormat:@"\r\n--%@--", kBOUNDARY];
    [mData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];

    return mData.copy;
}

Topics: iOS PHP network