如何通过 iOS 中的 JSON webservices post 方法将一组图像发送到服务器?
Posted
技术标签:
【中文标题】如何通过 iOS 中的 JSON webservices post 方法将一组图像发送到服务器?【英文标题】:How do I send an array of images to server through JSON webservices post method in iOS? 【发布时间】:2014-08-11 06:11:20 【问题描述】:我想知道如何使用UIImagePickerController
获取图像数组,并将数组发布到服务器,以及使用 JSON Web 服务从服务器获取图像数组。而且我还需要将图像信息(拍摄日期)发布到服务器。
我正在使用 UIImagePickerController 获取图像。这是我的代码
-(IBAction)fileselectionAction:(id)sender
[self.view endEditing:YES];
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Pick Photo From" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"Photo Album", @"Take New Photo", @"Cancel", nil];
[actionSheet showFromToolbar:self.navigationController.toolbar];
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
self.imagePickerController = [[UIImagePickerController alloc] init];
self.imagePickerController.delegate = self;
if (buttonIndex == 0)
//[self.imagePickerController setAllowsEditing:YES];
self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.imagePickerController.allowsEditing = YES;
[self presentViewController:self.imagePickerController animated:YES completion:nil];
else if (buttonIndex == 1)
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
[self.imagePickerController setAllowsEditing:YES];
//self.imagePickerController.showsCameraControls = YES;
[self presentViewController:self.imagePickerController animated:YES completion:nil];
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)info
[picker dismissViewControllerAnimated:YES completion:nil];
picker = nil;
NSData *imageData = UIImageJPEGRepresentation(image,0.0);
self.image1 = [UIImage imageWithData:imageData];
提前致谢。
【问题讨论】:
你可以使用这个库来支持任何类型的网络服务:github.com/mineshpurohit/ServiceCallingUtility 【参考方案1】:网络服务不提供发送图片的 API 吗?如果是这样,请使用它。
否则,如果您还自己开发 Web 服务,请不要使用 JSON 嵌入图像,而是使用适当的内容类型。
如果您绝对必须使用 JSON,则需要将图像编码为与 JSON 兼容的字符串,例如base64,然后将带有元数据的图像作为 JSON 字符串发送。
【讨论】:
- (NSString *)encodeToBase64String:(UIImage *)image NSLog(@"\n 结果字符串值为 %@",[UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]);返回 [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];我正在使用上述方法,但它花费了太多时间,而且我得到了很大的 base64 字符串值。 编码需要时间,但应该可以负担得起。通常,使用 base64 编码时,空间开销约为 25%,这是不可避免的。由于这个和其他原因,以 JSON 格式发送图像并不是最佳选择。如前所述,使用适当的内容类型。【参考方案2】:您应该使用 Multi-Part 请求一张一张地发送所有这些图像。以下是使用 AFNetworking 上传的链接。
https://github.com/AFNetworking/AFNetworking#post-multi-part-request
对于获取的数据;图像具有与拍摄日期相关的元数据。您可以从那里提取日期。
【讨论】:
以上是关于如何通过 iOS 中的 JSON webservices post 方法将一组图像发送到服务器?的主要内容,如果未能解决你的问题,请参考以下文章
如何通过 iOS 中的 JSON webservices post 方法将一组图像发送到服务器?