正确的方式嵌入json有效载荷base64与网络

问题描述:

在此先感谢您的任何帮助。我正在使用仅使用json有效内容的Web服务,并且此服务已设置为提交照片。正确的方式嵌入json有效载荷base64与网络

所以我想弄清楚在JSON有效载荷中嵌入图像的正确方法。这是我的方法。

//convert image to nsdata 
NSData *originalPhoto = UIImageJPEGRepresentation(self.photo.image,.9); 
//convert the data to a base64 string using NSData+Base64 category extension (Matt Gallagher version) 

NSString *base64photoString = [originalPhoto base64EncodedString]; 

//set the string in a NSDictionary 
[info setValue:base64photoString forKey:@"data"]; 

//then pass it to AFNetworking using the httpClient 

一切似乎工作,我得到json有效载荷。注意:bas64字符串在帖子正文中结束。

是否有人知道如果一个URI需要嵌入到数据的前面 - 如下所示:“file”:“data:image/jpg; base64,[base64 string]” - 我做过试试这个,但没有得到任何爱Web服务,但我可能有语法错误。

但是,网络服务并不喜欢它。

为了验证编码,我将生成的字符串从nslog中剪下来,并将其粘贴到在线解码器网站中,并重新创建原始图像 - 因此看起来数据编码正确。

在我可以与Web服务器管理员交谈之前两天,所以我只是在寻找验证这是一种正确的方法,或者请指出任何缺陷。我无法将服务更改为多部分编码形式,我坚持使用这种方法。

再次感谢

+0

你确定图像本身应该放入JSON吗?任何合理工作的WS我知道只用于元数据,实际的数据是在POST主体。 – 2012-08-05 05:18:39

+0

感谢您的回复。它确实作为json领域之一进入身体。我已经更新了有关URI的问题。 – CocoaEv 2012-08-05 12:59:40

得到这个想通了,我想我会把答案出来的情况下,任何人都有类似的问题。

方案 - 发布JSON有效载荷并将照片嵌入为base64string。

我在这里发现了base64的分叉版本。在其中包含了Matt Gallagher在2009年发布的最初作品中的另一种方法,名为:base64EncodedStringWithSeparateLines:YES - 这样做。

//use it like this: 
NSData *originalPhoto = UIImageJPEGRepresentation(self.photo.image,1); 
NSString *base64PhotoString = [originalPhoto base64EncodedStringWithSeparateLines:YES]; 

//stuff it in a dictionary like this: 
NSMutableDictionary *info = [NSMutableDictionary dictionary]; 
[info setValue:base64PhotoString forKey:@"sFileData"]; 

//send it using AFNetworking like this: 
[[ClientInterface sharedInstance] postPath:submitPhoto parameters:info success:^(AFHTTPRequestOperation *operation, id responseObject) { 

    NSLog(@"success!"); 

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

    NSLog(@"Error:%@",error); 

}];