Skip to content →

Month: April 2009

ASIHTTPRequest – Uploading Photos

Recently I used ASIHTTPRequest to upload images and other data from an iPhone application to a web server. I search around and looked at all the different options and this was best and easiest to use. It’s open source and comes with lots of good examples. I was particularly impressed with the network queue.

The one thing I did not find, was sample code for was posting an image to a server. Here is some sample code:

// Initilize Queue
[networkQueue setUploadProgressDelegate:statusProgressView];
[networkQueue setRequestDidFinishSelector:@selector(imageRequestDidFinish:)];
[networkQueue setQueueDidFinishSelector:@selector(imageQueueDidFinish:)];
[networkQueue setRequestDidFailSelector:@selector(requestDidFail:)];
[networkQueue setShowAccurateProgress:true];
[networkQueue setDelegate:self];

// Initilize Variables
NSURL *url;
ASIFormDataRequest * request;

// Add Image
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory 
     stringByAppendingPathComponent:@"myImage.jpg"];

// Get Image
NSData *imageData = [[[NSData alloc] 
     initWithContentsOfFile:dataPath] autorelease];

// Return if there is no image
if(imageData != nil){
	url = [NSURL URLWithString:@"http://myserver/upload.php"];
	request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
	[request setPostValue:@"myImageName" forKey:@"name"];
	[request setData:imageData forKey:@"file"];	
	[request setDidFailSelector:@selector(requestWentWrong:)];
	[request setTimeOutSeconds:500];
	[networkQueue addOperation:request];
	queueCount++;
}
[networkQueue go];	

Note: It’s not necessary to use a queue here because I’m only uploading 1 thing. But in my application I’m uploading many things and a queue was helpful. It also runs in the asynchronously in the background, which prevents the UI from getting locked up.

Note 2: When sending large files you should use “setFile” instead of “setData”. Files are then read from disk instead of memory. Here is an updated example. Thanks again to Ben Copsey for this library and his useful comments below.

NSString *imagePath = [documentsDirectory 
     stringByAppendingPathComponent:@"myImage.jpg"];
url = [NSURL URLWithString:@"http://myserver/upload.php"];
ASIFormDataRequest *request = 
    [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:@"myImageName" forKey:@"name"];
[request setFile:imagePath forKey:@"photo"];

More info on streaming here: http://allseeing-i.com/ASIHTTPRequest/How-to-use#streaming

16 Comments