correct way to embed base64 in json payload with a

2019-05-03 15:23发布

问题:

thanks in advance for any help. I am working with a web service that only takes json payloads and this service is setup for submitting photos.

So I am trying to figure out the proper way to embed an image in a json payload. This is my approach.

//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

everything seems to work and I get json payload. Note: the bas64 string ends up in the post body.

Is anyone aware of using this approach if an URI needs to be embedded in front of the data - something like this: "file":"data:image/jpg;base64,[base64 string]" - I did try this but not getting any love from the web service however I may have syntax wrong.

however the web service is does not like it.

To verify the encoding, I've cut the generated string out of nslog and pasted it into an online decoder web site and it re-creates the original image - so it looks like the data was encoded properly.

Its a couple of days before I can talk with the web server admin, so I'm just looking for verification that this is a correct approach or please point any flaws. I can't change the service to multi-part encoded form, I'm stuck with this approach.

thanks again

回答1:

Got this figured out and thought I'd put the answer out in case anyone else had a similar issue.

scenario - post a JSON payload with photo embedded as base64string.

I found a forked version of base64 here https://github.com/l4u/NSData-Base64.git. In included an additional method from the original work that Matt Gallagher posted circa 2009 called: base64EncodedStringWithSeparateLines:YES -- that did the trick.

//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);

}];