【问题标题】:correct way to embed base64 in json payload with afnetworking使用afnetworking将base64嵌入json有效负载的正确方法
【发布时间】:2012-08-02 14:08:06
【问题描述】:

提前感谢您的帮助。我正在使用一个只接受 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 中剪下生成的字符串并将其粘贴到在线解码器网站上,它会重新创建原始图像 - 因此看起来数据已正确编码。

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

再次感谢

【问题讨论】:

  • 您确定图像本身应该放入 JSON 中吗?我所知道的任何合理工作的 WS 仅将其用于元数据,实际数据在 POST 正文中。
  • 感谢您的回复。它确实作为 json 字段之一进入正文。我已经用关于 URI 的其他问题更新了我的问题。

标签: iphone ios json base64 afnetworking


【解决方案1】:

想通了这一点,并认为我会给出答案,以防其他人遇到类似问题。

场景 - 发布一个 JSON 有效负载,照片嵌入为 base64 字符串。

我在这里 https://github.com/l4u/NSData-Base64.git 找到了 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);

}];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-14
    • 2014-09-27
    • 2018-06-10
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多