1

我是 ios webservices 的新手,所以在过去的 2 到 3 天里我遇到了一个问题,我必须向服务器发送一个请求,它有多个部分,如图像和 json,我尝试使用 multipart/form-data 来发送我的请求,但由于某种原因服务器无法获得请求,谁能帮我解决这个问题

我正在使用的代码是

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]];
4

2 回答 2

0

直接使用 NSMutableURLRequest 感觉很复杂,请尝试使用“ASIFormDataRequest”,很好用。它们还具有许多其他功能,例如缓存响应、取消请求。文档在这里

于 2012-11-29T06:08:19.333 回答
0

所以,基本上我知道你在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...

现在,只需使用JSON之前使用的 。

有任何问题,请告诉我。:)

于 2012-11-29T06:14:58.083 回答