iOS upload multiple files

iOS upload multiple files

 

 

Upload file format

The HTTP /php/upload/upload.php the POST / 1.1 
the Host: 127.0 . 0.1 
the Content -Type: multipart / form-Data; boundary = identification (customizable) 
request body
 - identification (can be customized, but must request header consistent) 
the Content -Disposition: data-form; name = " userfile [] " ; filename = " head1.png " 
the Content -Type: Image / PNG 
blank lines 
file binary data
 - identifier (can be customized, but must request consistent header) 
the Content -Disposition: Data-form; name = " userfile [] " ; filename = " head2.png " 
the Content -Type: Image /png 
blank line 
binary file data
 - identifier (can be customized, but must be consistent with the request header) 
the Content -Disposition: Data-form; name = " Field Name " 

data values
 - identifying (can be customized, but must request head in agreement) -

Multi-file upload

 

#define kBOUNDARY @"abc"
- (void)viewDidLoad {
    [super viewDidLoad];
    // 网络链接
    NSString *netUrl = @"http://127.0.0.1/php/upload/upload-m.php";
    
    // 文件路径
    NSString *path1 = [[NSBundle mainBundle] pathForResource:@"head1.png" ofType:nil];
    NSString *path2 = [[NSBundle mainBundle] pathForResource:@"head2.png" ofType:nil];
    NSArray *array = @[path1, path2];
    
    // 字段名
    NSString *fieldName = @"userfile[]" ;
     // Data Dictionary 
    NSDictionary * dict = {@ @" username " : @" mazaiting " };
     // uploaded 
    [Self UploadFiles: netUrl the fieldName: filepaths the fieldName: Array the params : dict]; 
    
} 

// multiple file upload
 // netUrl network links
 // fieldName field name
 // filepaths file path array
 // params parameters 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(@"连接错误 %@", connectionError);
             return;
         }
         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
         if (httpResponse.statusCode == 200 || httpResponse.statusCode == 304) {
             // 解析数据
             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
             NSLog(@"%@",dict);
         } else {
             NSLog(@"服务器内部错误");
         }
     }];
}

// 构建请求体
- (NSData *)body:(NSString *)fieldName filePaths:(NSArray *)filePaths params:(NSDictionary *)params {
    NSMutableData *mData = [NSMutableData data];
//    ------WebKitFormBoundaryJa8BALfIc9saou2X
//    Disposition-the Content: Data-form; name = "userfile []"; filename = "head1.png"
 //     the Content-the Type: Image / PNG
 //     
//     file binary data
 //     ------ WebKitFormBoundaryJa8BALfIc9saou2X
 //     Disposition-the Content: data-form; name = "userfile []"; filename = "head2.png"
 //     the Content-the Type: Image / PNG
 //     
//     file binary data
 //     ------ WebKitFormBoundaryJa8BALfIc9saou2X
 //     Disposition-the Content: Data-form; name = "username"
 //     
//     mazaiting
 //     ------ WebKitFormBoundaryJa8BALfIc9saou2X-- 
    
    // build file, through the array
    [filepaths enumerateObjectsUsingBlock: ^ ( ID   _Nonnull obj, NSUInteger IDX, BOOL * _Nonnull STOP) {
 //               ------ WebKitFormBoundaryJa8BALfIc9saou2X
 //             the Content-Disposition: Data-form; name = "userfile []"; filename = "head2 The .png "
 //             the Content-the Type: Image / PNG
 //         
//             file binary data 
        
        the NSMutableString * mString = [the NSMutableString String ];
         // determines whether the first file, if it is not need to add" \ r \ n " 
        IF (! IDX = 0 ) { 
            [mString appendString: @ " \ R & lt \ 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]];
        // 拼接文件的二进制数据
        NSData *data = [NSData dataWithContentsOfFile:obj];
        [mData appendData: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]];
    }];
    
    // 结束语句
    NSString *end = [NSString stringWithFormat:@"\r\n--%@--", kBOUNDARY];
    [mData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];

    return mData.copy;
}

 

 

 

 

See: https: //yq.aliyun.com/articles/663460

Guess you like

Origin www.cnblogs.com/OIMM/p/11540406.html