Uploading image to server Detailed explanation for beginners

I have been working on uploading an image to the server in the last two days, since there are many questions about uploading an image via AFNetworking and NSURLSession and other ways of uploading everything that I ask, since I did not find a single answer explaining the whole concept of how everything works and what happens under the hood, I searched youtube and all things are available in Swift and do not trust me with any explanation whatsoever, and from my result I found that this answer is something that looks familiar to me



//Init the NSURLSession with a configuration NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]]; //Create an URLRequest NSURL *url = [NSURL URLWithString:@"yourURL"]; NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; //Create POST Params and add it to HTTPBody NSString *params = @"api_key=APIKEY& email=example@example.com &password=password"; [urlRequest setHTTPMethod:@"POST"]; [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; //Create task NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { //Handle your response here }]; [dataTask resume]; 


and also the most popular answer on this topic is User XJones : -

 Here code from my app to post an image to our web server: // Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept. NSMutableDictionary* _params = [[NSMutableDictionary alloc] init]; [_params setObject:[NSString stringWithString:@"1.0"] forKey:[NSString stringWithString:@"ver"]]; [_params setObject:[NSString stringWithString:@"en"] forKey:[NSString stringWithString:@"lan"]]; [_params setObject:[NSString stringWithFormat:@"%d", userId] forKey:[NSString stringWithString:@"userId"]]; [_params setObject:[NSString stringWithFormat:@"%@",title] forKey:[NSString stringWithString:@"title"]]; // the boundary string : a random string, that will not repeat in post data, to separate post data fields. NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"]; // string constant for the post parameter 'file'. My server uses this name: `file`. Your may differ NSString* FileParamConstant = [NSString stringWithString:@"file"]; // the server url to which the image (or the media) is uploaded. Use your server url here NSURL* requestURL = [NSURL URLWithString:@""]; // create request NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [request setHTTPShouldHandleCookies:NO]; [request setTimeoutInterval:30]; [request setHTTPMethod:@"POST"]; // set Content-Type in HTTP header NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant]; [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; // post body NSMutableData *body = [NSMutableData data]; // add params (all params are strings) for (NSString *param in _params) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; } // add image data NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0); if (imageData) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageData]; [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; } [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; // setting the body of the post to the reqeust [request setHTTPBody:body]; // set the content-length NSString *postLength = [NSString stringWithFormat:@"%d", [body length]]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; // set URL [request setURL:requestURL]; 


But I want to say that I studied myself, and it is very difficult to understand for a beginner without explanation, so all I ask is an explanation, a detailed explanation of the whole process, if it’s hard for someone to spend money on this question, because you believe or not. I have found this most difficult topic so far, because the main reason is that there are no textbooks throughout the process, as well as no explanations for beginners, if someone can take a step now and explain the concept, it will be easier for students who will study tomorrow. So anyone who can explain this in detail and how the download process works, and some steps for the link would be greatly appreciated.

Note I have an API and a key "image".

+7
ios objective-c xcode nsurlsession afnetworking
source share
3 answers

here we look at loading the images along with some ** parameters, because most of the time we load the image along with some parameters, such as userId.

  • Before delving into our topic, let me provide the code for creating the source material. All the details that we will see below relate to another stack overflow threads and some of the other sites, I have provided all the links for your reference.

     -(void)callApiWithParameters:(NSDictionary *)inputParameter images:(NSArray *)image imageParamters:(NSArray *)FileParamConstant{ //1 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setHTTPShouldHandleCookies:NO]; [request setTimeoutInterval:30]; [request setHTTPMethod:@"POST"]; //2 NSString *boundary = @"------CLABoundaryGOKUL"; //3 NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; //4 NSMutableData *body = [NSMutableData data]; for (NSString *key in inputParameter) { [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 stringWithFormat:@"%@\r\n", [inputParameter objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]]; } for (int i = 0; i < image.count; i++) { NSData *imageDatasss = UIImagePNGRepresentation(image[i]); if (imageDatasss) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant[i]] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageDatasss]; [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; } } [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; //5 [request setHTTPBody:body]; //6 [request setURL:[NSURL URLWithString:@"http://changeThisWithYourbaseURL?"]];//Eg:@"http://dev1.com/PTA_dev/webservice/webservice.php?" //7 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; //8 if ([httpResponse statusCode] == 200) { NSDictionary * APIResult =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"Response of %@: %@",[inputParameter valueForKey:@"service"],APIResult); }else{ //9 NSLog(@"%@",error.localizedDescription); } }]; } 

    NOTE. . Since this is a broad topic, I have provided a documentation link for more information.

    • We use ** NSMutableURLRequest ** instead of ** NSURLRequest ** because we are going to add some data to it. If you need some in-depth clarification regarding the modified URL request, go through this documentation .
      • setHTTPShouldHandleCookies here we have to decide whether we will use cookies or not. To learn more about visit
      • setTimeoutInterval , this helps to set a time limit for the url request. Add a time interval in seconds after the specified time, the request will be aborted.
      • setHTTPMethod has many methods . But we use GET and POST . The difference between POST and GET here and here
    • The border helps in separating the parameters from each other, so that the server can identify them. There can be any border, since your desire cannot edit it.
    • Here we use multipart / form-data; border = as a type of content. To know why we are going to use this type of content, check out this thread.
    • NSMutableData * body , we will add all parameters and values ​​to this data, and then setHTTPBody in UrlRequest .

      • If so we call the callApiWithParameters method

          - (IBAction)Done:(id)sender{ NSDictionary * inputParameters = [NSDictionary dictionaryWithObjectsAndKeys: @"1",@"user_id" , "XXX",@"name" , nil]; NSArray * image = [NSArray arrayWithObjects:[UIImage imageNamed:@"Test"],[UIImage imageNamed:@"Test1"],nil]; NSArray * imageParameters = [NSArray arrayWithObjects:@"img_one",@"img_two",nil]; [self callApiWithParameters:inputParameters images:image imageParamters:imageParameters]; } 
      • then the data (for example, the body) will look like this:

 Content-Type=multipart/form-data; boundary=------CLABoundaryGOKUL --------CLABoundaryGOKUL Content-Disposition: form-data; name=user_id 1 --------CLABoundaryGOKUL Content-Disposition: form-data; name=name XXX --------CLABoundaryGOKUL Content-Disposition: form-data; name=img_one; filename=image.jpg Content-Type:image/jpeg //First image data appended here --------CLABoundaryGOKUL Content-Disposition: form-data; name=img_two; filename=image.jpg Content-Type:image/jpeg //Second image data appended here. 
  • The above data will clearly explain what is happening, all parameters and keys have been added to the data. Here you can find more detailed information about sending multipart / form.

    1. Now just add the above data for the request [request setHTTPBody:body];
    2. setURL in this method add your base URL for your application.
    3. Now we need to make a connection to the server and send a request. We use NSURLConnection to send the request. Description of NSURLConnection Loads data for a request for a URL and executes a handler to block the operation queue when the request completes or fails.
    4. statusCode , which helps to find out if we received a successful response from the server. If 200 means OK, 500 means Internal Server Error, etc. More details here .

    5. Handle the error otherwise.

FYI I explained that I can, referring to links for a better understanding.

EDIT:

Just change the name in the imageParamater array. To satisfy your requirement, change img_one and img_two to an image .

  - (IBAction)Done:(id)sender{ //Change input parameters as per your requirement. NSDictionary * inputParameters = [NSDictionary dictionaryWithObjectsAndKeys: @"1",@"user_id" , "XXX",@"name" , nil]; NSArray * image = [NSArray arrayWithObjects:[UIImage imageNamed:@"Test"],nil]; //Change Test with your image name NSArray * imageParameters = [NSArray arrayWithObjects:@"image",nil];//Added image as a key. [self callApiWithParameters:inputParameters images:image imageParamters:imageParameters]; } 

and change point 6 using the base URL of your example,

// 6

  [request setURL:[NSURL URLWithString:@"http://google.com/files/upload.php?"]]; 
+4
source share

I think this is useful for you ...

 - (void)sendImageToServer { UIImage *yourImage= [UIImage imageNamed:@"image.png"]; NSData *imageData = UIImagePNGRepresentation(yourImage); NSString *base64 = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; NSString *strImage = [NSString stringWithFormat:@"data:image/png;base64,%@",base64]; NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:strImage,@"image", nil]; NSError * err; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&err]; NSString *UserProfileInRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSData *data=[UserProfileInRequest dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *len = [NSString stringWithFormat:@"%ld", (unsigned long)[data length]]; // Init the URLRequest NSMutableURLRequest *req = [[NSMutableURLRequest alloc] init]; [req setURL:[NSURL URLWithString:@"http://YOUR_URL"]]; [req setHTTPMethod:@"POST"]; [req setValue:len forHTTPHeaderField:@"Content-Type"]; [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [req setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [req setHTTPBody:data]; NSURLSession *session = [NSURLSession sharedSession]; [[session dataTaskWithRequest:req completionHandler:^(NSData *dt, NSURLResponse *response, NSError *err){ //Response Data NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:dt options:kNilOptions error:&err]; NSLog(@"%@", [dic description]); }]resume]; } 
+2
source share

Using AFNetworking For this task, which will give a very easy and reliable solution.

+1
source share

All Articles