Translate

Thursday, March 29, 2012

Upload an image and text from iPhone to Server

NSArray *formFields = [NSArray arrayWithObjects:@"stuid", @"parent_id", @"stu_name", @"gender", @"email", @"grade", @"dob", nil];
    NSArray *formValues = [NSArray arrayWithObjects:(id)childID, (id)parID, (id)childName, (id)childGender, (id)childMailID,(id)childGrade,(id)childDOB,nil];
    NSDictionary *textParams = [NSDictionary dictionaryWithObjects:formValues forKeys:formFields];
       
    NSArray *imageParams = [NSArray arrayWithObjects:childImage, nil];
   
    NSString *urlString = @"http://mysite.com/myscript.php";
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
   
    NSMutableData *body = [NSMutableData data];
   
    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
   
    // add the image form fields
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: attachment; name=\"image%d\"; filename=\"%@\"\r\n", 0, [imageParams objectAtIndex:0]] dataUsingEncoding:NSUTF8StringEncoding]];
   
        [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[NSData dataWithData:childImage]];
        [body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
           
    // add the text form fields
    for (id key in textParams) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:[textParams objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
   
    // close the form
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
   
    // set request body
    [request setHTTPBody:body];
   
    // send the request (submit the form) and get the response
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
   
    NSLog(@"%@", returnString);

No comments:

Post a Comment