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];
#else
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
#endif
[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];
}else{
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"];
try
{

//some check for the security

HttpPostedFile file = Request.Files.Count > 0 ? Request.Files[0] : null;
if (file == null)
{
Response.Output.Write("No file found");
Response.Output.Close();
return;
}
else
{
//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);
Response.Output.Write("Success");
Response.Output.Close();
return;
}
}
catch (Exception)
{
Response.Output.Write("Failure");
Response.Output.Close();
}
}
}

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.

Advertisements

About Mahmudul Islam

Senior Software Engineer Sitback Solutions (https://www.sitback.com.au/)
This entry was posted in IPhone, Mobile Developement and tagged , , , , , , , , , , , . Bookmark the permalink.

18 Responses to Uploading files from iPhone to ASP.net web site

  1. Bhavik Hingu says:

    I need sample Code if any….

    Like

  2. Bhavik Hingu says:

    I need sample code if any

    Like

  3. amit says:

    Thanks dude… It’s help me a lot

    Like

  4. tyegah says:

    Hi,

    Thanks for the tutorial. What if i want to save the image as binary to sql server? should i convert the httpinput to base64? and can i send the data as a string and just convert it to base64 on the server side? which way do you think is better?

    Like

    • tyegah says:

      oh one more thing, what’s the use of boundary string in your code?

      Like

      • Apology for a delayed reply, The example here is an old one, I am trying on a new implementation to upload larger files, may be 1 GB.

        if you send data using httprequest, then ASP will handle the file upload for you and the drawback is that there is a limitation on size, however if you upload binary chunks then you have to maintain the stream yourself and this also gives you the option to upload larger files.

        Like

  5. what is the namespace for Utility.GetID(IDType.File);

    Like

  6. It is not my first time to visit this site, i am browsing this website dailly and take pleasant data from here
    every day.

    Like

  7. rs says:

    How to upload video to server through iPhone app. Can you guide for that.

    Like

    • This post is for all kinds of file uploads, so of course video will be uploaded too, but however video files are usually larger in size and thus you might wanna use partial upload (instead of appending the whole file body, append parts of it and then use the same technique to upload the other parts and at server, join them to create the whole file) or try increasing request/response allowed byte size. I am working on a better version of it, but haven’t been able to finish it as I am experiencing some busy schedule.

      Like

  8. Collin says:

    I know this web site presents quality based content and other data, is there any other website
    which provides these kinds of stuff in quality?

    Like

  9. ram says:

    thanks a lot

    Like

  10. Gert says:

    Can I have the hole ASPX File with initializing ?

    Like

I would like to say something ...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s