How to Upload Multipart data of image in base64 Us

2019-04-15 04:41发布

I have used the following code but the response which i get is java.lang.NullPointerException & INTERNAL_SERVER_ERROR I tried many different methods but unable to fix it please help in fixing this.

Getting the Image from the Image picker

     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");
    }

Send the Image to server

  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条回答
We Are One
2楼-- · 2019-04-15 05:27
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);
    }];
}
查看更多
Viruses.
3楼-- · 2019-04-15 05:32

You can just use the appendPartWithFileData:name:fileName:mimeType: method of the AFMultipartFormData class.

For instance:

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);
}];
查看更多
放我归山
4楼-- · 2019-04-15 05:32

At last I made it work

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);
        }];
查看更多
登录 后发表回答