1

I want to send my image with parameter (username, password..etc) ?? following is my code:

-(void) senRequestForPostAnswerWithImage:(NSString *)imageName andAnswer:(NSString *)answer andQuestionID:(NSString *)questionID
{
    NSUserDefaults *loginData = [NSUserDefaults standardUserDefaults];
    NSString *username = [loginData objectForKey:@"username"] ;
    NSString *password = [loginData objectForKey:@"password"];

    NSString *postString = [NSString stringWithFormat:@"&username=%@&password=%@&image=%@&answer=%@&question_id=%@", username, password, imageName, answer, questionID];
    NSString *urlString = @"http://myAPIName/MethodName";
    NSURL *myURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSMutableURLRequest *detailRequestToServer =[NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
    [detailRequestToServer setHTTPMethod:@"POST"];
    [detailRequestToServer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    const char *utfString = [postString UTF8String];
    NSString *utfStringLenString = [NSString stringWithFormat:@"%zu", strlen(utfString)];
    [detailRequestToServer setHTTPBody:[NSData dataWithBytes: utfString length:strlen(utfString)]];
    [detailRequestToServer setValue:utfStringLenString forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:detailRequestToServer delegate:self];
    if (theConnection)
    {
        self.responseData = [[NSMutableData alloc] init];
        [GeneralClass startHUDWithLabel:@"Loading…"];
    }
    else
        NSLog(@"Connection Failed!");
}

I know there are many question on this site but I don't know where and what I need to change in my existing code ??

So, please suggest me what I need to change in my existing code for add functionality of send image ??

NOTE: without image this above code is working well for me.

βhargavḯ
  • 9,786
  • 1
  • 37
  • 59

6 Answers6

2

My suggestion would be to use AFNetworking. It will simplify the process for your considerably and save you a lot of time. It is widely used framework by developers.

https://github.com/AFNetworking/AFNetworking

You can easily send image with parameters using just few lines (POST-multipart request):

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
Ajay
  • 1,622
  • 20
  • 36
1

As far as I know, you can't directly send it as UIImage. You need to convert it to NSData, which the gets decoded on the server side.

Another alternative, is to upload the image somewhere, which can be accessed via a URL. (But this is usually done on the server side and the URL is given back as response).

There's a post here about converting UIImage to NSData.

Community
  • 1
  • 1
Lord Zsolt
  • 6,492
  • 9
  • 46
  • 76
1

using this you can pass parameters as well as with image data.

NSString *urlString = [NSString stringWithFormat:@"http://myAPIName/MethodName/test.php&username=%@&password=%@&image=%@&answer=%@&question_id=%@", username, password, imageName, answer, questionID];
NSLog(@"MyURL: %@",urlString);

urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];

[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------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 *str=[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"SourceImage\"; filename=\"Image_%@\"\r\n",[imagePath lastPathComponent]];
[body appendData:[[NSString stringWithString:str] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithContentsOfFile:imagePath]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
βhargavḯ
  • 9,786
  • 1
  • 37
  • 59
  • @Bhargavi right now i have an issue and your code works perfect but it not upload image when server is secure. have you tried this code when security enable server side ? – JAY RAPARKA Oct 12 '15 at 12:03
  • @Bhargavi please replay me as soon as possible. Thank you and please replay me. – JAY RAPARKA Oct 12 '15 at 12:04
0

If you want to send parameter with image by post method then use following code. Its working very well for me..

I tried to change my code as per your requirement, follow it.
You need to create NSMutableDictionary and add your parameter on it and also append this dictionary to NSMutableData as JSON formate. (You need to add NSMutableData Library to your project)

-(void) senRequestForPostAnswerWithImage:(NSString *)imageName andAnswer:(NSString *)answer andQuestionID:(NSString *)questionID
{
    NSUserDefaults *loginData = [NSUserDefaults standardUserDefaults];
    NSString *username = [loginData objectForKey:@"username"] ;
    NSString *password = [loginData objectForKey:@"password"];

     // create NSMutableDictionary for store parameter
    NSMutableDictionary *dicOfData = [[NSMutableDictionary alloc] init];
    [dicOfData setObject:username forKey:@"username"];
    [dicOfData setObject:password forKey:@"password"];
    [dicOfData setObject:imageName forKey:@"imageName"];
    [dicOfData setObject:answer forKey:@"answer"];
    [dicOfData setObject:questionID forKey:@"questionID"];

    NSString *url =  @"http://myAPIName/MethodName";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
    [request setHTTPMethod:@"POST"];

    /// create NSMutableData to store data of dictionary
    NSMutableData *body = [NSMutableData data];    
    NSString *boundary = @"--iOS Boundary Line--";
    [request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField: @"Content-Type"];

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

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString  *imgPath = [documentsDir stringByAppendingPathComponent:imageName];
    if([imageName length] > 0)
    {
        if([[NSFileManager defaultManager] fileExistsAtPath:imgPath])
        {
            [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"photo\"; filename=\"%@\"\r\n", imageName] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[NSData dataWithContentsOfFile:imgPath]];
            [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"requestData\"\r\n\r\n%@", [dicOfData JSONRepresentation] ] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:body];
    [request addValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (theConnection)
    {
        self.responseData = [[NSMutableData alloc] init];
    }
    else
        NSLog(@"Connection Failed!");
}

At your server (PHP) side.. you get image (object and name if you added) with other parameter in dictionary formate.

iPatel
  • 46,010
  • 16
  • 115
  • 137
-1

Refer this code - It works perfect for me -

NSString *userID = mainDelegate.loginUserPin;

UIImage *imag = self.addImage;

NSString *urlString = mainDelegate.I2K2_Webservice_Url;

NSData *imageData = UIImageJPEGRepresentation(imag, 90);

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

NSString *boundary = @"*****";
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]];

//Title
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"title\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@~%@",userID,txtName.text] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//Description
[body appendData:[@"Content-Disposition: form-data; name=\"description\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

NSString *imgNameString = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"%@~%@\"\r\n",userID,txtName.text];

NSLog(@"imgNameString : %@",imgNameString);

[body appendData:[[NSString stringWithString:imgNameString] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"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);
Abizern
  • 146,289
  • 39
  • 203
  • 257
iSmita
  • 1,292
  • 1
  • 9
  • 24
-1

You cant send UIImage by specifying it's name to web server. You should include it in the HTTP body as NSData .I used ASIHTTPRequest, it was simple and perfect. Use ASIHTTPRequest. A sample code is given below

NSData *imgData = UIImageJPEGRepresentation(IMAGE_HERE, 0.9);
formReq = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlString]];
formReq.delegate = self;
[formReq setPostValue:VALUE1 forKey:KEY1];
[formReq setPostValue:VALUE2 forKey:KEY2];
if (imgData) {
    [formReq setData:imgData withFileName:@"SAMPLE.jpg" andContentType:@"image/jpeg" forKey:IMAGE_KEY];
}
[formReq startSynchronous];
manujmv
  • 6,450
  • 1
  • 22
  • 35
  • 1
    ASIHTTP is pretty much dead now see this link: http://stackoverflow.com/questions/8636418/asihttprequest-vs-afnetworking-framework – Ajay Nov 21 '13 at 12:39