使用multipart/mixed在ios中上载图像和json

使用multipart/mixed在ios中上载图像和json,ios,Ios,我是ios网络服务的新手,所以在过去的2到3天里,我一直遇到一个问题, 我必须向服务器发送一个请求,该服务器有多个部分,如图像和json,我试图使用多部分/表单数据发送我的请求,但由于某种原因,服务器无法获得请求,有人能帮我解决这个问题吗 我使用的代码是 NSData *imageData = UIImagePNGRepresentation(img); NSMutableURLRequest *theRequest =[NSMutableURLRequest requestWithUR

我是ios网络服务的新手,所以在过去的2到3天里,我一直遇到一个问题, 我必须向服务器发送一个请求,该服务器有多个部分,如图像和json,我试图使用多部分/表单数据发送我的请求,但由于某种原因,服务器无法获得请求,有人能帮我解决这个问题吗

我使用的代码是

NSData *imageData = UIImagePNGRepresentation(img);

   NSMutableURLRequest *theRequest =[NSMutableURLRequest requestWithURL:theURL];

    NSString *boundary = [NSString stringWithFormat:@"---------------------------14737809831466499882746641449"];

 NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];

    [theRequest addValue:contentType forHTTPHeaderField:@"Content-Type"];
[theRequest setHTTPMethod:@"POST"];


 NSMutableString *theBody = [[NSMutableString alloc]init];

    [theBody appendString:[NSString stringWithFormat:@"\r\n--%@\r\n", boundary]];

     [theBody appendString:[NSString stringWithFormat:@"Content-Type: application/json\r\n\r\n"]];

//append The Json string

[theBody appendString:myJsonString];

[theBody appendString:[NSString stringWithFormat:@"%@", boundary]]; 

//this appends the image

[theBody appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"data\"; filename=\"photo\""]];

[theBody appendString:[NSString stringWithFormat:@"Content-Type: image/png\r\n\r\n"]];

[theBody appendString:[NSString stringWithFormat:@"%@",imageData]];

[theBody appendString:[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] ];

[theRequest setHTTPBody:[theBody dataUsingEncoding:NSUTF8StringEncoding]];

我觉得直接使用NSMutableURLRequest很复杂,请尝试使用ASIFormDataRequest,它很容易使用。它们还有许多其他功能,比如缓存响应、取消请求。文档是。

因此,我得到的基本信息是,在JSON中发送图像时,您会遇到问题

在这种情况下,首先可以在NSData中分解图像,然后在该数据中需要Base64编码器方案,如下所示:

[Base64 encode:(NSData)data]
NSMutableDictionary* dict = [NSMutableDictionary new];
[dict setObject:[Base64 encode:data] forKey:@"imageBytes"]; // I did in single step but if you need you can do two steps...
现在,您可以存储在所需的结构中,比如说,如果您需要存储在字典中,那么您可以实现相同的功能,如:

[Base64 encode:(NSData)data]
NSMutableDictionary* dict = [NSMutableDictionary new];
[dict setObject:[Base64 encode:data] forKey:@"imageBytes"]; // I did in single step but if you need you can do two steps...
现在,只需像前面一样使用JSON


如果有任何问题,请告诉我

您好,Mohit谢谢您的帮助,但我将面临的问题是,通过将其编码为base64,它将使文件大小增加33%。这就是我寻找多部分的原因。您可以帮助我处理多部分请求吗?嘿,我只是将一个示例放在:。检查它,可能它会解决你的问题。这是我在尝试Base64编码之前使用的同一代码,它不起作用…我的疑问是,我们是否必须在服务器端配置一些东西来接受多部分请求,因为服务器正在给多部分servlet解析错误嘿,可能您正在使用J2EE作为后端,在这种情况下,我不知道更多。但是,如果您仔细检查我为您提供链接的代码,您会发现您编写的一些更改。在我这边,它运行得很好。