HTTP POST请求发送图像

时间:2014-05-12 09:21:54

标签: ios image post nsurlrequest

我试图通过HTTP POST请求将图片发布到网络服务。

API文档说,图像参数应该是您要分析的图像的二进制文件数据 - 仅限PNG,GIF,JPG。"

这是我尝试使用的代码:

UIImage *image = [UIImage imageNamed:@"air.jpg"];
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
    NSURLResponse *response;
    NSError *error = nil;

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://pictaculous.com/api/1.0/"]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:imgData];

    NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
                                                 returningResponse:&response
                                                             error:&error];

    if(error!=nil) {
        NSLog(@"web service error:%@",error);
    }
    else {
        if(receivedData !=nil) {
            NSError *Jerror = nil;
            NSDictionary* json =[NSJSONSerialization
                                 JSONObjectWithData:receivedData
                                 options:kNilOptions
                                 error:&Jerror];
            if(Jerror!=nil) {
                NSLog(@"json error:%@",Jerror);
            }
        }
    }

问题是在JSON响应中我总是收到错误"你必须提供一个图像"好像收到的图像格式不正确。

Isn'" UIImageJPEGRepresentation"从图像中获取二进制数据的正确方法是什么?

还有其他方法可以从JPEG图像中获取二进制文件数据吗?

谢谢, 的Corrado

1 个答案:

答案 0 :(得分:0)

如果您想简化代码,可以使用简单的NSURLConnection包装,例如STHTTPRequest

STHTTPRequest *r = [STHTTPRequest requestWithURLString:@"http://pictaculous.com/api/1.0/"];

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"];
NSData *data = [NSData dataWithContentsOfFile:path];

[r addDataToUpload:data parameterName:@"image"];

r.completionBlock = ^(NSDictionary *headers, NSString *body) {
    NSLog(@"-- %@", body);
};

r.errorBlock = ^(NSError *error) {
    NSLog(@"-- error: %@", error);
};

[r startAsynchronous];