iOS_Passion
iOS_Passion

Reputation: 788

How to upload image to a url using post request asynchronously?

I have to upload an image to a specific url. The specifications that I have to follow are these: 1. Method should be post 2. Image must be uploaded using multipart HTTP content type 3. The name of the HTTP field should be “uploadingTheFile”. 4. Multipart data shiuld have filename. 5. Image content type should be among following-jpeg,jpg,png,gif

I want to upload using NSURLConnection asynchronously. I think I am not able to set the parameters in the request in a proper way.I am getting status code as 200 which suggests that there is no problem with my NSURLConnection delegate methods. The code that I am trying is :

NSString *stringBoundary=@"0xKhTmLbOuNdArY";
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary] forHTTPHeaderField:@"uploadfile"];


NSMutableData *postBody = [NSMutableData data];
NSData *imageData=UIImagePNGRepresentation([UIImage imageNamed:@"IMG_0215.JPG"]);

//[postBody appendData:imageData];
[postBody appendData:[@"Content-Disposition: form-data; name=\"data;filename=\"media.png\"\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:imageData]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:postBody];

NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
    self.data = [NSMutableData data];
}

Upvotes: 0

Views: 1950

Answers (3)

omanosoft
omanosoft

Reputation: 4339

You can use AFNetworking (it is opensource), here is code that worked for me. This is for AFNetworking 3.0 version.

NSString *serverUrl = [NSString stringWithFormat:@"http://www.yoursite.com/uploadlink", profile.host];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:serverUrl parameters:nil error:nil];


NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];


manager.responseSerializer = [AFHTTPResponseSerializer serializer];

NSURL *filePath = [NSURL fileURLWithPath:[url path]];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
     dispatch_async(dispatch_get_main_queue(), ^{
                //Update the progress view
                LLog(@"progres increase... %@ , fraction: %f", uploadProgress.debugDescription, uploadProgress.fractionCompleted);
            });
        } completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error) {
                NSLog(@"Error: %@", error);
            } else {
                NSLog(@"Success: %@ %@", response, responseObject);
            }
        }];
[uploadTask resume];

Upvotes: 0

SachinVsSachin
SachinVsSachin

Reputation: 6427

Here you can learn how to use afnetworking for upload images

https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ

Upvotes: 0

Ankur Arya
Ankur Arya

Reputation: 4723

I am using following code and it is working fine for me.

NSData *imageData = UIImageJPEGRepresentation(empImgView.image, 90); // convert image in NSData
    NSString *urlString = @"http://abc.com/saveimage/Default.aspx"; // your url

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = [NSString stringWithString:@"---------------------------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--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    NSString *imgNameString = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n",[responseSrting substringWithRange:NSMakeRange(1, responseSrting.length - 2)]];    
    [body appendData:[[NSString stringWithString:imgNameString] 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];

    NSLog(@"%@",returnString);

Upvotes: 1

Related Questions