Send an image from the iPhone using ASIHTTP and UIImagePicker
Using examples such as the one below from this website I am trying to send a photo selected with 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(@" %@ ", ima开发者_运维百科geURL);
stringURL = [imageURL absoluteString];
I don't get how to connect these two chunks of code. I would like to use this url to locate the image on my iPhone and then send it with the ASIHTTP code. Any ideas?
First you need to save the image and keep track of the filename or filepath. Here I used a time interval to create unique image names. photoImage is the UIImage that you want to store.
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];
Then you go and grab the file path using the filename that you stored or if you already stored the file path then skip to the next bit.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:photoName];
Then we make the HTTP request to send the data at said file path.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.requestMethod = @"POST";
[request setFile:filePath forKey:@"file1"];
[request startSynchronous];
精彩评论