如何使用afnetworking上传base64中图像的多部分数据

时间:2016-06-09 13:55:59

标签: ios objective-c afnetworking image-uploading multipartform-data

我使用了以下代码,但我得到的回复是java.lang.NullPointerException& INTERNAL_SERVER_ERROR我尝试了很多不同的方法,但无法修复它,请帮助解决这个问题。

从图像选取器中获取图像

     UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
     Profilebackground.image = chosenImage;
    [picker dismissViewControllerAnimated:YES completion:NULL];
    NSURL *resourceURL;
    UIImage *image =[[UIImage alloc] init];

    image =[info objectForKey:@"UIImagePickerControllerOriginalImage"];

    NSURL *imagePath = [info objectForKey:@"UIImagePickerControllerReferenceURL"];

    imageName = [imagePath lastPathComponent];

    resourceURL = [info objectForKey:UIImagePickerControllerReferenceURL];



    NSString *extensionOFImage =[imageName substringFromIndex:[imageName rangeOfString:@"."].location+1 ];

    if ([extensionOFImage isEqualToString:@"JPG"])
    {
        imageData =UIImageJPEGRepresentation(image, 1.0);
        base64 = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        extension=@"image/jpeg";

    }

    else
    {
        imageData =  UIImagePNGRepresentation(image);
        base64 = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        extension=@"image/png";
    }

    int imageSize=imageData.length/1024;

    NSLog(@"imageSize--->%d", imageSize);
    if (imageName!=nil) {
        NSLog(@"imageName--->%@",imageName);
    }
    else
    {
        NSLog(@"no image name found");
    }

将图像发送到服务器

  AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        [manager POST:@"https://blahblahblah.com/uploadProfileImg?userId=1" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            //NSData *pngData = [[NSData alloc] initWithBase64EncodedString:base64 options:1];
            [formData appendPartWithFileData:imageData
                                        name:@"key"
                                    fileName:imageName mimeType:extension];

        }  success:^(NSURLSessionDataTask *task, id responseObject) {
            NSLog(@"Response: %@", responseObject);
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            NSLog(@"error: %@",error);
        // NSHTTPURLResponse *response = (NSHTTPURLResponse *)operation.response;
            NSLog(@"statusCode: %ld", (long)response.statusCode);
            NSString* ErrorResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
           NSLog(@"Error Response:%@",ErrorResponse);
        }];

3 个答案:

答案 0 :(得分:0)

您可以使用appendPartWithFileData:name:fileName:mimeType:类的AFMultipartFormData方法。

例如:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

[manager POST:@"https://blahblahblah.com/imageupload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData
                                name:@"key name for the image"
                            fileName:photoName mimeType:@"image/jpeg"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"Response: %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Error: %@", error);
}];

答案 1 :(得分:0)

Please try the below code in AFNetworking 2.0.3
Hope this will helpful for u

- (void) createNewAccount:(NSString *)nickname accountType:(NSInteger)accountType primaryPhoto:(UIImage *)primaryPhoto
{
    // Ensure none of the params are nil, otherwise it'll mess up our dictionary
    if (!nickname) nickname = @"";
    NSLog(@"Creating new account %@", params);

    [self POST:@"accounts" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFormData:[nickname dataUsingEncoding:NSUTF8StringEncoding] name:@"nickname"];
        [formData appendPartWithFormData:[NSData dataWithBytes:&accountType length:sizeof(accountType)] name:@"type"];
        if (self.accessToken)
            [formData appendPartWithFormData:[self.accessToken dataUsingEncoding:NSUTF8StringEncoding] name:@"access_token"];
        if (primaryPhoto) {
            [formData appendPartWithFileData:UIImageJPEGRepresentation(primaryPhoto, 1.0)
                                        name:@"primary_photo"
                                    fileName:@"image.jpg"
                                    mimeType:@"image/jpeg"];
        }
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"Created new account successfully");
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"Error: couldn't create new account: %@", error);
    }];
}

答案 2 :(得分:0)

最后我开始工作

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        [manager POST:@"https://blahblahblah.com/uploadProfileImg?userId=1" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

            [formData appendPartWithFileData:imageData
                                        name:@"key"
                                    fileName:imageName mimeType:extension];

        }  success:^(NSURLSessionDataTask *task, id responseObject) {
            NSLog(@"Response: %@", responseObject);
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
            NSLog(@"error: %@",error);

            NSLog(@"statusCode: %ld", (long)response.statusCode);
            NSString* ErrorResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
           NSLog(@"Error Response:%@",ErrorResponse);
        }];