How to add header in Multipart Form data request iOS?

时间:2015-09-14 15:23:17

标签: ios iphone image-uploading afnetworking-2 multipartform-data

Following is my code snippet. I am getting an error while runnning this code. I have added headers as part of the request. Is that the correct way ?

         __block int i=1;
         AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
         NSDictionary *parameters = @{@"wave_Id": [inputDictionary objectForKey:@"wave_Id"]};
         AFHTTPRequestOperation *op = [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

             for(NSData *imageData in [inputDictionary objectForKey:@"images"])
             {
                 [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"file%d",i] fileName:[NSString stringWithFormat:@"abc%d.png",i] mimeType:@"image/png"];
                 i++;
             }
             NSError *error;
             NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
             NSAssert(jsonData, @"Failure building JSON: %@", error);
             NSLog(@"Json Data Image Upload %@",jsonData);
             NSAssert(jsonData, @"Failure building JSON: %@", error);
             NSString *token = [SSKeychain passwordForService:RegistrationTokenKey account:LoggedInUserKey];

             NSDictionary *jsonHeaders = @{@"Content-Disposition" : @"form-data; name=\"parameters\"",
                                           @"Content-Type"        : @"application/json",
                                           @"Accept"              : @"application/json",
                                           @"Authorization"       : token};
             [formData appendPartWithHeaders:jsonHeaders body:jsonData];

         } success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"Error: %@ ***** %@", operation.responseString, error);
         }];
         [op start];

2 个答案:

答案 0 :(得分:0)

I need your complete method to be 100% sure, but please try writing this way and see if it helps:

__block int i = 1;
NSMutableArray *mutableOperations = [NSMutableArray array];
NSDictionary *parameters = @{@"wave_Id": [inputDictionary objectForKey:@"wave_Id"]};

for (NSData *imageData in [inputDictionary objectForKey:@"images"]) {

    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"
                                                                                       URLString:url
                                                                                      parameters:parameters
                                                                       constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData
                                   name:[NSString stringWithFormat:@"file%d",i]
                               fileName:[NSString stringWithFormat:@"abc%d.png",i]
                               mimeType:@"image/png"];
        i++;
    }
                                                                                           error:nil];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [mutableOperations addObject:operation];
}


NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
    NSLog(@"%lu of %lu images uploaded!", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
    NSLog(@"All images have been uploade!");
}];

[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

答案 1 :(得分:0)

实际上我修改了相同的代码并且现在正在使用它。更改了&#34;内容类型&#34; to&#34; multipart / form-data&#34;。 还在API请求中将我的imagesArray的键(参数名称)添加到以下方法中 &#34; formData appendPartWithFileData:imageData name:@&#34; yourKey&#34; ...&#34;

if(_isUploadImage){

         __block int i=1;
         AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
         [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
         [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
         if (_shouldBeInHeader) {
             NSString *token = [SSKeychain passwordForService:RegistrationTokenKey account:LoggedInUserKey];
             [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",token] forHTTPHeaderField:@"Authorization"];
         }
         NSDictionary *parameters = @{@"wave_id": [inputDictionary objectForKey:@"wave_id"]};
         AFHTTPRequestOperation *op = [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

              for (NSData *imageData in [inputDictionary objectForKey:@"images"])
             {
                [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"images"] fileName:[NSString stringWithFormat:@"abc%d.png",i] mimeType:@"image/png"];
                 i++;
             }

            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSLog(@"Success");
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Failed");
         }];

         [op start];
         }