Upload image file to server in iOS.

In this tutorial we will upload the image as a file to JSON server .
For uploading image as a file we use multipart form as our content type .








Now jumping straightforward to our code .

Step 1 :  Add AFNetworking framework to your project .

               How to add AFNetworking to your project ?
               Visit my previous post on AFNetworking .



Step 2:   Import AFNetworking to your project.

             #import <AFNetworking/AFNetworking.h>




Step 3:   Add the following code in viewDidLoad to upload image as a file :


UIImage *image = [UIImage imageNamed:@"joker.png"]; // name of the image
NSData *imageData = UIImagePNGRepresentation(image); // convert your image into data
NSString *urlString = [NSString stringWithFormat:@"YOUR URL"]; // enter your url to upload
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // allocate AFHTTPManager
[manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { // POST DATA USING MULTIPART CONTENT TYPE
[formData appendPartWithFileData:imageData
name:@"yourParameter"
fileName:@"image.jpg" mimeType:@"image/jpeg"]; // add image to formData
[formData appendPartWithFormData:[@"sdsd" dataUsingEncoding:NSUTF8StringEncoding]
name:@"key1"]; // add your other keys !!!
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"Response: %@", responseObject); // Get response from the server
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"Error: %@", error); // Gives Error
}];
view raw MultipartNew hosted with ā¤ by GitHub


Thats all about file uploading in iOS .

Thank you :) .

Comments

  1. This doesn't work. It is long known bug in AFnetworking. There is a workaround to do this. See here: https://github.com/AFNetworking/AFNetworking/issues/1398

    ReplyDelete
    Replies
    1. Hi UTSAV , it is working code. If you have any queries you can ping me anytime.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. hi saurabh it will be helpful if u share the code here

    ReplyDelete
    Replies
    1. I have already shared my code in this tutorial

      Delete
  5. hello y dont u share code which works!!!

    ReplyDelete
    Replies
    1. Hi Vahida, If you have any queries you can mail me at saurabh23july@gmail.com

      Delete
    2. Hi saurabh , If we want to provide some authentication to urllike username and password How can we provide?

      Delete
  6. Thanks for this beautiful post IOS. It is really good for the beginners and I also liked the post.
    IOS Training in Bangalore
    IOS Training in Marathahalli

    ReplyDelete
  7. I got to know more about the ios. Thanks for sharing this blog.
    android-vs-ios

    ReplyDelete

Post a Comment

Popular Posts