Uploading files from iPhone to ASP.net web site

Hello All,

As a coder sometimes I have to crush my head on the desk for not finding a feasible solution to a problem. One problem that almost had me finished is uploading image files from iPhone to asp.net website. Both the website and iPhone application was developed by me and thus I had to find both the solution –

  • Uploading file data to the site
  • Then collecting that data and saving to folder
  • Passing additional parameters so that I can run security checks about the user who is uploading the file and also track for which item the file is being uploaded.

After Googling a lot I came to two very important posts at stackoverfow that helped me figure out the process of doing this. It was a long time ago so, I can’t remember the addresses of the post, so I just thought I can summarize the full process so that anyone who is about to break his skull can get some help. Ok, enough talk, lets see the process.

1. Selecting files from iPhone

First you need to able to select files from your iPhone. Anyone who has come this far can easily design a view that can select a file with the UIImagePickerControl. I used a UITextBox that was used to select the image. When user click on the textbox the image picker is shown and user then selects the image. After selecting the image the image is shown in a UIImageView under the textbox for review. Here is the code sample that does it ( I have removed unnecessary codes, so just copying won’t work, you have to merge it).

- (BOOL) textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return TRUE;

- (void)textFieldDidBeginEditing:(UITextField *)textField{
if(textField == filename){
[description resignFirstResponder];
[filename resignFirstResponder];
//show file select dialog

UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
[imagePicker setDelegate:self];
#ifdef __i386__
[imagePicker setSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentModalViewController:imagePicker animated:YES];

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)img
editingInfo:(NSDictionary *)editingInfo{
[picker dismissModalViewControllerAnimated:YES];
[self.image setImage:img];


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissModalViewControllerAnimated:YES];

Don’t worry about the #ifdef used here, this is just a check that If the app is running from the simulator then it will not throw an exception. Here textField is the text field used to select the image and self.image is the UIImageView used to preview the image to the user. This also has a hidden use, I also used it as the image data cache when sending the file data to the server.

2. Sending file data to server

At the server, I just used a .aspx file to catch the uploaded file and then write a response to indicate if the file was collected or not. I will discuss about the page later, lets just see how we are to send the data to the server.

Once, the user selects the file, the image data is saved in the UIImageView used to preview the image. I just collected the data from the UIImageView and sent it to the server by manually appending into a HTTP post request.

- (IBAction) Upload{
NSData *imageData = UIImagePNGRepresentation([self.image image]);
NSString *urlString = [NSString stringWithFormat:@"http://%@/iphone/Upload.aspx?wid=%@&sskey=%@",[[SettingsManager instance] nurl],[[SettingsManager instance] wid],[[SettingsManager instance] sskey]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[NSData dataWithData:imageData]];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

if([returnString isEqualToString:@"Success"]){
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Upload" message:@"File successfully uploaded" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Upload" message:@"File upload failed" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
[returnString release];

The task is pretty simple, just grab the image data from the imageView, then append manually with the boundary, set the content type for the HTTP request and post the data. Don’t worry about the values used from SettingsManager class, this is a singleton class that I used to save data cache, nurl is the url to be used for sending data, wid is the id that will be associated with the file and sskey is the session key used to check for security. Just ignore the if part here we will discuss it later. We are now halfway through, now all we need a aspx page to save the file content. The next section will do that.

3. Saving file content

The aspx is very simple page with the following code at the page load to save the file content. I took the wid, and sskey from the url and the file from the httpinput stream and saved as necessary.

public partial class iphone_Upload : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
String wid = Request.QueryString["wid"];
String sskey = Request.QueryString["sskey"];

//some check for the security

HttpPostedFile file = Request.Files.Count > 0 ? Request.Files[0] : null;
if (file == null)
Response.Output.Write("No file found");
//Get an entry for file upload
string fileName = Utility.GetID(IDType.File);

String[] names = file.FileName.Split('.');
string src = fileName + "." + names[names.Length - 1];

file.SaveAs(Server.MapPath("~/userhud/uploads/") + src);
catch (Exception)

The code is simple. Just get the file and other values and manipulate as necessary. One thing you might notice I outputed ‘Success’ or ‘Failure’ directly to the stream and closed it. In this case that If block that we used in 2, will come in hand to notify user about successful or failed uploads. The Utility.GetID() is a method I used to generate a unique id for each file uploaded to overcome the fact that I might overwrite s file while uploading.

4. Conclusioin

In this post I have tried to summarize the process of uploading image files from iPhone to ASP.Net web sites. Hope that this might be helpful for you. Your suggestions are always welcome.