forHTTPHeaderField:@“content-type”用于图像和数据

时间:2012-02-04 09:46:39

标签: iphone objective-c post content-type nsurlrequest

我想使用我的iphone应用程序中的POST方法将用户图片和用户的其他信息发送到服务器。

我的内容类型如下

NSString *boundary = [NSString stringWithString:@"--"];
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

但它只发布图片。我的其他数据没有在服务器上发布。

如果我使用以下内容类型,那么

[ request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

然后它只发送其他数据。不发送图片。

请建议我发送图像和其他信息的方式。

2 个答案:

答案 0 :(得分:0)

使用Base64对图像进行编码,如下所示

[Base64Coder encodeData:UIImagePNGRepresentation(image)];

您可以从this link下载Base64课程。

已修改:已添加代码示例

NSString *reqStr = [NSString stringWithFormat:@"iPhone_request=<game><name>%@</name><image>%@</image></game>",txtGameName.text, [Base64Coder encodeData:UIImagePNGRepresentation(imgGame.image)]];

// Replace occurrences of + with %2B
reqStr = [[reqStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
reqData = [reqStr dataUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:reqData];

答案 1 :(得分:-2)

使用ASIHTTPRequest简单易用:)