使用ASIHTTP和UIImagePicker从iPhone发送图像

时间:2011-09-10 19:09:21

标签: iphone objective-c http

使用this website下面的示例我试图发送使用UIImagePickerController选择的照片。

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:@"Ben" forKey:@"names"];
[request addPostValue:@"George" forKey:@"names"];
[request addFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photos"];
[request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg" forKey:@"photos"];

imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
NSLog(@"  %@ ",  imageURL);
stringURL = [imageURL absoluteString];

我不知道如何连接这两个代码块。我想用这个url在我的iPhone上找到图像,然后用ASIHTTP代码发送它。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

首先,您需要保存图像并跟踪文件名或文件路径。在这里,我使用时间间隔来创建唯一的图像名称。 photoImage是您要存储的UIImage。

NSTimeInterval timeInterval = [NSDate timeIntervalSinceReferenceDate];
NSString *photoName=[NSString stringWithFormat:@"%lf-Photo.jpeg",timeInterval];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:photoName];
NSData * photoImageData = UIImageJPEGRepresentation(photoImage, 1.0);
[photoImageData writeToFile:appFile atomically:YES];

然后你使用你存储的文件名抓取文件路径,或者如果你已经存储了文件路径,那么跳到下一位。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:photoName];

然后我们发出HTTP请求以在所述文件路径上发送数据。

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.requestMethod = @"POST";
[request setFile:filePath forKey:@"file1"];
[request startSynchronous];