【发布时间】:2014-05-14 16:12:13
【问题描述】:
我正在尝试通过 HTTP POST 请求将图像发布到网络服务。
API 文档说 image 参数应该是“您要分析的图像的二进制文件数据 - 仅限 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 响应中,我总是收到错误“您必须提供图像”,就好像接收到的图像格式不正确一样。
“UIImageJPEGRepresentation”不是从图像中获取二进制数据的正确方法吗?
有没有其他方法可以从我的 JPEG 图像中获取二进制文件数据?
谢谢, 科拉多
【问题讨论】:
-
把你的uimage转成base64编码,然后把字符串传给服务器,
-
永远记住,你不能将图像直接存储到服务器中,你需要遵循 3 个步骤,1.你的图像 2.将 UIImage 赋予 NSData 3.将 NSData 赋予 NSString 然后最后将字符串传递给服务器,
-
您是否检查过您的图像已成功存储在服务器路径中
-
我将 NSData *imgData = UIImageJPEGRepresentation(image, 1.0) 替换为 NSString *imgData = [UIImageJPEGRepresentation(image, 1.0) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength] 并修改了 [request setHTTPBody:[imgData dataUsingEncoding:NSUTF8StringEncoding] 行] 但我总是得到同样的错误。这是您建议的正确实施吗?谢谢
-
实际上你无法将图像发布到服务器或从服务器获取图像
标签: ios image post nsurlrequest