4

我正在尝试将图像添加到我想在服务器上发布的 JSON 文件中。我正在使用以下代码,但我不断收到Invalid type in JSON write (NSConcreteMutableData)错误。代码是

NSDictionary *parameter = [[NSDictionary alloc]init];
NSData *imageData = UIImagePNGRepresentation(imageView.image);
parameter = @{@"body":@"Hi",@"image":imageData};

另外,我正在使用AFNetworking将图像发布到服务器

我不确定代码中有什么问题。任何帮助将不胜感激

4

2 回答 2

3

如果其他人以后有同样的问题。这是您应该使用的代码

NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSDictionary *parameter = @{@"body":@"image"};
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:parameter constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];

来源:链接

于 2013-03-26T07:38:41.877 回答
1

试试这样

parameter = @{@"body":@"Hi",@"image":[NSString stringWithFormat:@"%@" ,imageData]};
于 2013-03-26T06:56:08.563 回答