AFNetworking:使用其他参数上传图像

时间:2013-12-05 07:13:48

标签: ios json afnetworking-2

首先,感谢您阅读此问题。

我正在开发使用JSON webservice的应用程序。在应用程序中,我需要使用带有一些参数的图像(配置文件图像)调用webservice。 我的JSON请求应该与以下内容相同......

{
  "adduser": {
  "firstname": "testFirstName",
  "lastname": "testLastName",
  "email": "test@test.com",
  "projectids" : "1"
  }
  }

还有其他变量profileimage用于上传图片。

我写了以下代码。

    NSDictionary *dictParameter = @{@"adduser": @{@"firstname": firstName, @"lastname":lastName,@"email":email, @"projectids":@"1"}};
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFHTTPRequestOperation *op = [manager POST:strURL parameters:dictParameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"Error: %@ ***** %@", operation.responseString, error);
            }];
 [op start];

以上代码记录跟随错误。

Error: <br />
<b>Notice</b>:  Undefined index: json in <b>/opt/lampp/htdocs/testproject/app/webroot/webservices/include.php</b> on line <b>15</b><br />
{"status":"failure","message":"Your Request is Empty"} ***** Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x8abe490 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

如果我使用以下代码而不是正常工作。但我无法上传图片。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
   [manager POST:strURL parameters:dictParameter success:^(AFHTTPRequestOperation *operation, id responseObject) {

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];

由于

4 个答案:

答案 0 :(得分:1)

您缺少实际添加要发送到服务器的图像数据的部分。

NSDictionary *dictParameter = @{@"adduser": @{@"firstname": firstName, @"lastname":lastName,@"email":email, @"projectids":@"1"}};

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *op = [manager POST:strURL parameters:dictParameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:@"image" error:nil];
        } 
success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
            } 
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"Error: %@ ***** %@", operation.responseString, error);
            }];

 [op start];

查看有关posting a multi-part request的AFNetworking文档。

答案 1 :(得分:0)

使用 ASIFormDataRequest 库查看以下代码。

-(IBAction)postPhotoButtonClickedButtonClicked:(id)sender
{
    [textViewStatusBox resignFirstResponder];
    NSLog(@"postPhotoButtonClicked");
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self presentModalViewController:picker animated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *randomPictureName = [NSString stringWithFormat:@"%@.png", [self generateRandomString]] ;
    [picker dismissModalViewControllerAnimated:YES];
    UIImage *selectedImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    NSData *imageData = UIImagePNGRepresentation(selectedImage);
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://webber.im/iphone/post_library.php"]];
    [request setPostValue:@"ASv48umPgx0tyuu9PnjxcQ" forKey:@"key"];
    [request addData:imageData withFileName:randomPictureName andContentType:@"multipart/form-data" forKey:@"picture"];
    [request setDelegate:self];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        NSString *response = [request responseString];
     }
    }

这里我有两个参数图片。您可以使用自己的参数进行修改。 希望它能帮到你很多。

干杯

答案 2 :(得分:0)

最后,我发现JSON + formdata(图像)不能与AFNetworking一起使用。 所以,我把一个任务分成两个, 1)使用AFNetworking formData appendPartWithFileURL功能上传图像 2)成功上传图像后,从服务器响应中获取图像名称。使用该图像名称调用添加用户Web服务。

现在正在运作。

答案 3 :(得分:0)

NSMutableDictionary * dicData = [[NSMutableDictionary alloc] initWithCapacity:1];

[dicData setObject:placeName forKey:@"name"];

[dicData setObject:[NSNumber numberWithFloat:latitude] forKey:@"latitude"];

[dicData setObject:[NSNumber numberWithFloat:longitude] forKey:@"longitude"];

[dicData setObject: [NSNumber numberWithLong:categoryId] forKey:@"categoryId"];

[dicData setObject:@"1" forKey:@"userId"];

number=arc4random();
NSLog(@"Random Number=%d",number);

str=[NSString stringWithFormat:@"%d",number];

AFHTTPRequestOperation *op = [manager POST:insertPlaceData parameters:dicData constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

    //do not put image inside parameters dictionary as I did, but append it!

    [formData appendPartWithFileData:imgData name:@"image" fileName:[str stringByAppendingString:@".jpg"] mimeType:@"image/jpeg"];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
     //   NSLog(@"JSON: %@", [responseObject description]);

        MainScreen *mainScreen=[[MainScreen alloc]init];
        [self.navigationController pushViewController:mainScreen animated:YES];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      //  NSLog(@"Error: %@", [error description]);
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving data"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];

    }];