如何将图像从iOS发送到Web服务

时间:2013-06-10 02:58:43

标签: ios image web-services

我想将图片上传到iOS的网络服务。在Web服务中,image参数数据类型为File。我想发送用户从手机摄像头拍摄的图像的拇指。任何人都可以说如何将拇指图像从iOS应用程序发送到Web服务。

感谢。

2 个答案:

答案 0 :(得分:4)

使用AFNetworking,你可以通过以下方式完成:

NSURL *url = [NSURL URLWithString:@"my_base_url"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"yourImage.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"MainMedia" fileName:@"MainMedia" mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];

[operation start];

答案 1 :(得分:2)

如果您正在使用ASIHttpRequest库,请查看以下代码:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:yourRequestURL]];

[request addRequestHeader:@"User-Agent" value:@"ASIHTTPRequest"]; 
[request addRequestHeader:@"Content-Type" value:@"application/json"];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,     NSUserDomainMask, YES);
NSString *savedImagePath = [NSString stringWithFormat:@"%@/%@/%@",[paths objectAtIndex:0],folder,imageName];

if ([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath])
    [request setFile:savedImagePath forKey:@"imgfile"];
[request setRequestMethod:@"POST"];
[request setDelegate:self];
[request setDidFailSelector:@selector(requestFailed:)];

我希望它会对你有所帮助。