2

I m supposed to post the session ID, that is generated during validation of credentials and image data. But the image and session ID is not uploaded. It was working fine when I used ASIHTTPRequest, later when i tried with NSMutableUrlRequest and NSURLConnection it doesnot seem to work.

Given below is the code used to POST image and Session ID

- (void)postinDataToServer:(NSData *)inData
{
//inData is the image data.
[inData retain];  
NSString *urlString = @"http://xyz.com/abcd/kgh.php";
NSURL* url = [NSURL URLWithString:urlString];

NSMutableData *photoData = [[NSMutableData alloc]init];

//SessionID is stored in NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSString * boundary = @"photoBoundaryParm";
NSString * boundaryString = [NSString stringWithFormat:@"--%@\r\n", boundary];
NSString * boundaryStringFinal = [NSString stringWithFormat:@"--%@--\r\n", boundary];

[photoData appendData:[boundaryString dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"SessionID\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:[[NSString stringWithFormat:@"SessionID=%@",[defaults objectForKey:@"SessionID"]] dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

[photoData appendData:[boundaryString dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"photo\";\r\nfilename=\"myphoto.png\"\r\nContent-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:inData];
[photoData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

[photoData appendData:[boundaryStringFinal dataUsingEncoding:NSUTF8StringEncoding]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:photoData];

NSString* requestDataLengthString = [[NSString alloc] initWithFormat:@"%d", [photoData length]];

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

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self
                        startImmediately:NO];

[connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                      forMode:NSDefaultRunLoopMode];
[connection start];

[inData release];
inData = nil;
}

Please help.

I m stuck with this for really long time.

Thanks in advance.

Joran Den Houting
  • 3,149
  • 3
  • 21
  • 51
user1899840
  • 543
  • 2
  • 7
  • 19
  • In your connection delegate methods, do you hit the success callback? (If its the failure one, please provide the actual error, though by the sounds of things it is hitting success, just not posting the image - just want to eliminate the obvious problems first!) – David Doyle Oct 01 '13 at 13:44
  • Do you really have to do it manually? Have you considered trying AFNetworking (see http://stackoverflow.com/questions/15410689/iphone-upload-multipart-file-using-afnetworking) – Vadim Yelagin Oct 01 '13 at 13:51
  • delgate methods didReceiveResponse, didReceiveData and connectionDidFinishLoading are called. But didFailWithError is not called. @DavidDoyle – user1899840 Oct 03 '13 at 05:37
  • I m trying to create a framework, so wanted to avoid third party as much as possible. I used ASIHTTPRequest intially and it was working fine. But I had other issues during integration of my framework to other apps, so switched to the above mentioned method. @VadimYelagin – user1899840 Oct 03 '13 at 05:38
  • Did you check this? http://nthn.me/posts/2012/objc-multipart-forms.html Worked for me. – kubilay Feb 18 '14 at 21:22

2 Answers2

1

try this code, and pass your values in post nsstring

NSString* url=[NSString stringWithFormat:url];

NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURLURLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
                                                        cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                    timeoutInterval:60.0];
//do post request for parameter passing
[theRequest setHTTPMethod:@"POST"];

NSString *post = [NSString stringWithFormat:@"&imageData=%@",postData];



NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];


[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPBody:postData];

[theRequest  setURL:[NSURL URLWithString:url]];

[theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];

NSURLConnection  *serverConnectionObj = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
YogiBhoi
  • 169
  • 1
  • 10
0

this is a class method solution:

header

//=========================
// POST FORM WITH IMG
//=========================
+ (NSData *)postToUrl:(NSURL*)url
                 form:(NSDictionary*)form
             andImage:(UIImage*)img
             imageKey:(NSString*)imageKey
                error:(NSError**)error
    returningResponse:(NSURLResponse**)response;

Class method:

#pragma mark -
#pragma mark POST FORM
//=========================
// POST FORM
//=========================
+(NSData *)postToUrl:(NSURL*)url form:(NSDictionary*)form andImage:(UIImage*)img imageKey:(NSString*)imageKey error:(NSError**)error returningResponse:(NSURLResponse**)response{
    NSLog(@"postToUrl:%@ Form:%@ andImage:%@ imageKey:%@",url,form,img,imageKey);
    NSString *boundary = @"iOS_iKANIMO_BOUNDARY_STRING";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];

    NSMutableData *body = [NSMutableData data];

    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"photo.png\"\r\n", imageKey] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:UIImagePNGRepresentation(img)]];



    for (NSString*key in [form allKeys]) {
        NSLog(@"%@ - %@",key,[form objectForKey:key]);
        NSString *value = [form objectForKey:key];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@",key, value] dataUsingEncoding:NSUTF8StringEncoding]];
    }


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

    //Now all we need to do is make a connection to the server and send the request:
    [request setHTTPBody:body];
    return [NSURLConnection sendSynchronousRequest:request returningResponse:response error:error];
}
ikanimo
  • 481
  • 1
  • 4
  • 18