4

提前感谢您的帮助。我正在使用一个只接受 json 有效负载的 Web 服务,并且该服务是为提交照片而设置的。

所以我试图找出将图像嵌入到 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]” - 我确实尝试过但没有得到来自网络服务的任何爱,但是我可能有语法错误。

但是网络服务不喜欢它。

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

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

再次感谢

4

1 回答 1

3

弄清楚了这一点,并认为我会提出答案,以防其他人遇到类似问题。

场景 - 发布一个 JSON 有效负载,照片嵌入为 base64string。

我在这里找到了 base64 的分叉版本 https://github.com/l4u/NSData-Base64.git。其中包括 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);

}];
于 2012-08-06T18:24:43.457 回答