6

我一直在寻找新的 AFNetworking 2.0 上传图像的示例。但是我碰壁了,无法弄清楚代码有什么问题。所以这是我使用的代码

NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];


AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://myserverurl.com"];

NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromData:imageData progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"Success: %@ %@", response, responseObject);
    }
}];
[uploadTask resume];

TIA

4

1 回答 1

34

我最终使用了多部分请求

UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFormData:imageData name:@"image"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
于 2013-10-09T23:22:01.687 回答