Post a UIImage to the web

So here is something a lot of people have been wondering to do in the forums. How do I take a UIImage or any image and post it to a website. So this will go over how to do that.

There are two ways to tackle this issue. One we can base64 encode the file and post is normally inside a XML or JSON instance or we can simulate a normal HTML post. This tutorial will go over the HTML post.

This will start off where Using a UIImagePickerController left off. So you can grab the code and start there if you want. So lets begin.

So first open up testPickerViewController.h and we want to add in one outlet and one action.

So here is the outlet we want to add
IBOutlet UIButton *upload;
Here is the action we want to add
IBOutlet UIButton *upload;
Now double click on testPickerViewController.xib and we need to connect the new outlet and action. We also need to create our new upload button. So drag around the current items and place the new button under the grab button. Then you want to make the button hidden by default. The option is as shown below. Do get to that selector you do Tools -> Attributes Inspector

You might also want to setup your UIImageView to aspect fit. If the image is larger then your box you created in IB it will shrink the image to fill it. Click on the UIImageView and in the Attributes Inspector select the following drop down for Mode

Now you want to make your connections to the new outlet and action we created in code. So here is another screenshot of what they should look like

Now it is back to the code. So save this and you can quit IB. 

So open up testPickerViewController.m and find the imagePickerController method and at the end add 
upload.hidden = NO;

That will show our upload button once a image is set.

So now we need to create our uploadImage method that gets called then the button is pressed. So it is below and hopefully pretty well commented.

- (IBAction)uploadImage {
	/*
	 turning the image into a NSData object
	 getting the image back out of the UIImageView
	 setting the quality to 90
	*/
	NSData *imageData = UIImageJPEGRepresentation(image.image, 90);
	// setting up the URL to post to
	NSString *urlString = @"http://iphone.zcentric.com/test-upload.php";

	// setting up the request object now
	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];

	/*
	 add some header info now
	 we always need a boundary when we post a file
	 also we need to set the content type

	 You might want to generate a random boundary.. this is just the same
	 as my output from wireshark on a valid html post
	*/
	NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
	NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
	[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

	/*
	 now lets create the body of the post
	*/
	NSMutableData *body = [NSMutableData data];
	[body appendData:[[NSString stringWithFormat:@"rn--%@rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name="userfile"; filename="ipodfile.jpg"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-streamrnrn"] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[NSData dataWithData:imageData]];
	[body appendData:[[NSString stringWithFormat:@"rn--%@--rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
	// setting the body of the post to the reqeust
	[request setHTTPBody:body];

	// now lets make the connection to the web
	NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

	NSLog(returnString);
}

So now if you build and go you will upload the image you selected to the following image URL

http://iphone.zcentric.com/uploads/ipodfile.jpg

Below is my PHP file I am using to handle uploads.

$uploaddir = './uploads/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        echo "http://iphone.zcentric.com/uploads/{$file}";
}

It is nothing special. I do an echo so you can see in the console what the file is. If you switch the filename=”" part in the uploadImage section it will be placed as another file.

Files will be removed once they are 10 minutes old on the server so they won’t last but you can use it as a playground.

As always here is my code.

About mike
Currently works for OpenSky as a Senior Linux Admin. He has a wonderful wife Thanuja and 2 great dogs. His major side project is Photoblog.

Comments

113 Responses to “Post a UIImage to the web”
  1. jay says:

    Matthew may i see your code in asp.net? well i and my friend has tried to create in aspx file but it can’t work at all. Please help..

    • Justin says:

      give me a hand.

      I upload jpg file to web server in xcode simulator.
      system error information as follows:

      “missing boundary in input” upload fail

      who know this problem? please help thanks.

  2. Matthew Bryant says:

    This works in asp.net!!!!!!!!!!!!!!!!!!!

    HttpFileCollection MyFilecollection = Request.Files;

    MyFilecollection[0].SaveAs(Server.MapPath(“~/ImageStore/” + MyFilecollection[0].FileName));

  3. Matthew Bryant says:

    Full code is shown below.Replace test-upload.php with your asp page (mine is recievefile.aspx)

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web.Security;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.Odbc;
    using System.Data.SqlClient;
    using System.Diagnostics;
    using System.IO;
    using System.Web.Util;
    using System.Reflection;
    using System.Drawing;
    using System.Net;

    using System.Text.RegularExpressions;

    public partial class recievefile : System.Web.UI.Page
    {

    public DatabaseGateway dg = new DatabaseGateway();

    protected void Page_Load(object sender, EventArgs e)
    {

    HttpFileCollection MyFilecollection = Request.Files;

    MyFilecollection[0].SaveAs(Server.MapPath(“~/ImageStore/” + MyFilecollection[0].FileName));

    }
    }

    MyFilecollection[0].SaveAs(Server.MapPath(“~/ImageStore/” + MyFilecollection[0].FileName));

    }

  4. Matthew Bryant says:

    Sorry repeated a bit of code at bottom of last post. If you need any help anyway reply on this forum. Thanks to the author of this post which allowed me to get started and work out the asp solution

  5. Gemma says:

    Hi there is there a way of

    taking the picture- then straight away uploading it?
    Hope to hear back, thanks in advance :)
    Gemma

  6. Dipen says:

    @ Matthew,

    Hi Matthew, i have tried your code to upload image but we are not getting success. From application we are using same code as shown in the tutorial but at server side they are not getting any file in the request so can you please help us?

    Here is the code for design in asp

    Untitled Page

    Cheers,
    Dipen

  7. Dipen says:

    @ Matthew,

    Also Matthew, do we need to convert image data in base64 string or not?

  8. xcode starter says:

    Can someone please give me the test-upload.php file?

  9. jay says:

    @matthew,
    well sorry for the late reply.. it seems your code doesn’t work too.. in the iphone it looks success (from debug) but in server.. i couldn’t find the specified file

  10. Yang says:

    Hi, I tried your method, but doesn’t work on my location. I can not find the uploaded file. By the way, do you have any ideas on video uploading ?

  11. Jaibabu says:

    Hello Sir,

    I was really happy on seeing your code for uploading images to the server through iPhone. It worked great. I was trying to upload audio and video files too. I added some code to upload video file. But i was stuck up in the middle. First thing in the simulator video files are not listed in the picker Controller. Secondly how to send the video files instead of imageData.

  12. Jaibabu says:

    Hai,

    I had found a way to list video files in the simulator PickerController. If i select the video file it is getting selected and file is ready to play. If i click the play button the video gets played in the simulator. But if i click on the Choose button the simulator goes on compressing the video file but not transferring control to didFinishPickingImage function. Can the compressing be avoided in the simulator and read the video content and sent to the server to store the video file.

    Thanks
    Jaibabu

  13. Lee says:

    I changed the buttons to a toolbar with two buttons, how can I hide the upload button as you do with the UIButton? I have tried a few other resources but I can’t find any that work…

    All I did is change UIButton to UIBarButtonItem to work with the buttons.

  14. IPhoneStruggler says:

    hey nice one and very helpful.I have a problem i have two viewcontrollers and am using pickercontroller in firstview to pick an image and i want to pass that image to secondview controller.am not getting this..
    please help me

  15. marco says:

    i try many times with asp.net but don’t work, can someone post a correct .aspx document?

  16. marco says:

    i try also with your asp code but return this error: BC36008: ‘Using’ must end with a matching ‘End Using’.

    the php solution works

  17. Amit says:

    cool post friend…keep it up…

  18. Alice says:

    > parse the incoming data.. It is a random
    > string that must be the same.

    How can it be both totally random… and “the same”????

  19. Patty says:

    How would I change that code to upload an image from my camera-roll… to ImageShack.com?

  20. retool2 says:

    awesome guy, with awesome tutorial

  21. xcodemaddy says:

    How to Insert image into Mysql database Using Php?plz post some php code to save image into DB.Help me

  22. Sneha says:

    hey seriously nice tutorial i can upload any type of my file on the server

    • sachin says:

      hi,

      i needs to upload photos to server… from me the coding which provides above is not working.Can u guide me how to solve this..

      Thanks in advance

  23. Sneha says:

    I am getting video from the photo library but cannot post to the server can anyone help!!!

  24. ander says:

    Hi!!
    I am building an application, and the code seems to work just final, until I receive the file on the server, which is something called Resource id #3.
    Doest anyone know who to fix this?? thank you very much!!

  25. gokay says:

    awesome tutorial,thanks

  26. xCoder says:

    Being new to asp.net but needing to process incoming images with an aspx, What kind of project do i create in VS10 to get Matthews code to work?

    When I do a copy paste into a MVC app, i get errors for lines:
    public DatabaseGateway dg = new DatabaseGateway();

    Error 12 The type or namespace name ‘DatabaseGateway’ could not be found (are you missing a using directive or an assembly reference?) C:VS10 CodeMvcApplication4MvcApplication4ControllersHomeController.cs 24 8 MvcApplication4

    AND

    MyFilecollection[0].SaveAs(Server.MapPath(“~/ImageStore/” + MyFilecollection[0].FileName));

    (16 errors, heres 2 of them)
    Error 14 Only assignment, call, increment, decrement, and new object expressions can be used as a statement C:VS10 CodeMvcApplication4MvcApplication4ControllersHomeController.cs 28 44 MvcApplication4

    Error 16 The name ‘ImageStore’ does not exist in the current context C:VS10 CodeMvcApplication4MvcApplication4ControllersHomeController.cs 28 46 MvcApplication4

    Thanks

  27. Arun says:

    Am receiving the error “Index out of range” while trying to upload an image to .net server ? Am fighting with this error for the past three months..i came across a lot of blogs and tried with lot other stuffs adding few lines in server side coding …everything in vain !!!!!!! Kindly help me out getting a solution for this issue …

  28. krzyhoo says:

    Hi
    You can post image to asp.net page in two ways:
    1) just create .aspx page and add in form declaration: enctype=”multipart/form-data
    2) create ASP.NET Generic Handler (.ashx file) which doesn’t have any HTML code.

    I also added to iPhone’s code, in webservice address to parameters as query string: path to directory and file name.

    My code is like that:
    1)
    // .aspx file

    // .aspx.cs file

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;

    public partial class PostPhoto : System.Web.UI.Page
    {

    protected void Page_Load(object sender, EventArgs e)
    {
    bool HasParsingErrors = false;
    HttpFileCollection filesPosted = Request.Files;
    String filePath = Request.QueryString["TargetPath"];
    String fileName = Request.QueryString["TargetName"];

    try
    {
    if (String.IsNullOrEmpty(fileName) || String.IsNullOrEmpty(filePath) || filesPosted.Count <= 0)
    HasParsingErrors = true;

    if (HasParsingErrors)
    {
    WriteFile(filesPosted[0], filePath, fileName);
    HttpContext.Current.Response.ContentType = "text/plain";
    HttpContext.Current.Response.Write("Success");
    }
    else
    {
    context.Response.Write("Failed: parsing error");
    }
    }
    catch (Exception ex)
    {
    context.Response.Write("Failed: exception error:::" + ex.Message);
    }
    }

    private void WriteFile(HttpPostedFile file, String filePath, String fileName)
    {
    Directory.CreateDirectory(filePath);
    int counter = 1;
    string path = String.Format("{0}\Photos\{1}-1.jpg", filePath, fileName);
    while (File.Exists(path))
    {
    counter++;
    path = String.Format("{0}\Photos\{1}-{2}.jpg", filePath, fileName, counter);
    }

    file.SaveAs(path);
    }
    }

    2) Generic handler:

    using System;
    using System.Web;

    public class PostPhoto : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = “text/plain”;
    bool hasErrors = false;
    HttpFileCollection filesPosted = context.Request.Files;
    String filePath = context.Request.QueryString["TargetPath"];
    String fileName = context.Request.QueryString["TargetName"];
    try
    {
    if (String.IsNullOrEmpty(fileName) || String.IsNullOrEmpty(filePath) || filesPosted.Count <= 0)
    hasErrors = true;

    if (!hasErrors)
    {
    WriteFile(filesPosted[0], filePath, fileName);
    HttpContext.Current.Response.Write("Success");
    }
    else
    {
    context.Response.Write("Failed: parsing error");
    }
    }
    catch (Exception ex)
    {
    context.Response.Write("Failed: exception error:::" + ex.Message);
    }

    }

    private void WriteFile(HttpPostedFile file, String filePath, String fileName)
    {
    System.IO.Directory.CreateDirectory(filePath);
    int counter = 1;
    string path = String.Format("{0}\Photos\{1}-1.jpg", filePath, fileName);
    while (System.IO.File.Exists(path))
    {
    counter++;
    path = String.Format("{0}\Photos\{1}-{2}.jpg", filePath, fileName, counter);
    }

    file.SaveAs(path);
    }

    public bool IsReusable {
    get {
    return false;
    }
    }

    }

  29. Arun says:

    Hello krzyhoo,

    Are you able to access the NSDATA from iphone and store it in the server.

    We face a great problem in that..

    the .net coding is similar to yours..

  30. Arun says:

    We receive the file with exact size..but it is unreadable ..when we try to open , it says NO PREVIEW AVAILABLE..

    do you receive the image in .net as NSDATA or something else..

  31. Carlos says:

    I,m trying to complmpile this code in OS4.0. I gt errors in UIKit.framewrk and CorelGraphics.framework. Any information abut it?

  32. pablo says:

    as would be the case with zip files ?

  33. vkspune says:

    Great job dude.
    Its really great.

  34. Jayesh Italiya says:

    I liked this tutorial and your work both it is too good and helfull for me can you please send me the php file on mine email.

  35. Venkat says:

    Awesome post.. everything to test end to end is provided..and works jus perfectly…

  36. Sebastian Gaag says:

    Thanks

  37. jordan Brown says:

    how could you send, from the iphone, a message to the server which added data to a plist.
    OR
    sent a text document.(with content)
    OR entered data into a pre existing text document.

  38. ganesh says:

    i need to upload the video to the server. For that i am using UIImagePickerController. When i am selecting the video that is in Photos library it is going on by showing “Compressing Video”. So can u help me in this regard

  39. ganesh says:

    hai can u give me the code snippet for video uploading please…

  40. M Arshad says:

    what does mean ‘failed to open stream’?
    any tip will be appreciated!

    2011-07-22 17:20:13.455 testPicker[28365:207]
    Warning: move_uploaded_file(./images/ipodfile.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/clamor/public_html/FileUploader.php on line 7

    Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move ‘/tmp/phpx4ND5o’ to ‘./images/ipodfile.jpg’ in /home/clamor/public_html/FileUploader.php on line 7
    Terminating in response to SpringBoard’s termination.

  41. Nimish Agarwal says:

    Hi, awesome tutorial. I have tried the code and it is working really great.

    I have a small problem. Everything is working from sending to saving the file. But the image which is getting saved is flip/inverse of the actual image taken. Any ideas why it is happening?

    -Nimish

  42. mohsin says:

    move_uploaded_file(./uploads/0d7eefd0aee4f1b.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in D:wampwwwdemoupload.php on line 12

  43. Nitin Gautam says:

    Do you have Java Version of this?

  44. inveni0 says:

    Hello, and thank you for this helpful guide! I was using some different code, and it would connect to the server but not actually do the upload. And that’s why I came to your page. It seems, however, that your code throws a 403 error on my server. Any idea why this might be?

    • inveni0 says:

      Apparently, this is due to server restrictions with cross-site multipart/form-data. I’ve contacted my hosting company for assistance. But if there’s a workaround (besides using .htaccess) involving ASI, I’d be interested in hearing it!

  45. Mahesh says:

    Thanks for your nice information. i works for me very well.
    Mahesh

  46. MaxSmall says:

    Good tutorial!

    But how can i upload some image ?
    The first uploaded image is named “ipodfile.jpg” and when I upload an other image is overwrite.

    How I can fixe this ?
    Thanks

  47. Dipanjan Dutta says:

    Upload from device:

    The above example works fine from simulator. But how do I run it on device that is what should I do if I want to upload images from my device?

    Thanks in advance for any help.

  48. Haritha says:

    Used this logic,data received on the Java server is null.
    When i send a base64 encoded string to java server,its failing to draw the image on server side.

  49. Rahul says:

    Its really going to help me to upload an image on to the server.
    thanks a lot..

Trackbacks

Check out what others are saying about this post...
  1. [...] is a blog post about it Post a UIImage to the web | Iphone Noob Here is the meat of the code to post [...]

  2. [...] have a blog post about this Post a UIImage to the web | Iphone Noob Looks like your boundaries are bad __________________ Iphone Noob iPhone Development Blog. [...]

  3. [...] this? Post a UIImage to the web : Iphone Noob __________________ My Apps on AppStore : gScale (guitar scales reference), [...]

  4. [...] is a blog post about it Post a UIImage to the web | Iphone Noob Here is the meat of the code to post [...]

  5. [...] Post a UIImage to the web : Iphone Noob (tags: iphone programming photoupload) This entry was posted on Thursday, March 10th, 2011 at 6:06 pmand is filed under del.icio.us. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]

  6. [...] I have found quite a bit of advice on the matter on the internet but nothing I try seems to work. This is my objective-c code, based on the tutorial here: http://iphone.zcentric.com/2008/08/29/post-a-uiimage-to-the-web/ [...]



Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!