ios - Uploading image to server Detail Explanation for Beginner -


i'm working on uploading image server last 2 days there tons of questions uploading image through afnetworking , nsurlsession , other methods of uploading i'm asking didn't found single answer explaining whole concept how things work , going on under hood searched youtube stuff available in swift , trust me no explanation @ , result found answer looks familiar me



    //init nsurlsession configuration nsurlsessionconfiguration *defaultconfigobject = [nsurlsessionconfiguration defaultsessionconfiguration]; nsurlsession *defaultsession = [nsurlsession sessionwithconfiguration: defaultconfigobject delegate: nil delegatequeue: [nsoperationqueue mainqueue]];  //create urlrequest nsurl *url = [nsurl urlwithstring:@"yoururl"]; nsmutableurlrequest *urlrequest = [nsmutableurlrequest requestwithurl:url];  //create post params , add 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 response here }];  [datatask resume]; 


and popular answer topic user xjones is:-

here's code app post image our web server:  // dictionary holds post parameters. can set post parameters server accepts or programmed 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"]];  // boundary string : random string, not repeat in post data, separate post data fields. nsstring *boundaryconstant = [nsstring stringwithstring:@"----------v2ymhfg03ehbqgzcako6jy"];  // string constant post parameter 'file'. server uses name: `file`. your's may differ  nsstring* fileparamconstant = [nsstring stringwithstring:@"file"];  // server url image (or media) uploaded. use 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 strings) (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 body of post reqeust [request sethttpbody:body];  // set content-length nsstring *postlength = [nsstring stringwithformat:@"%d", [body length]]; [request setvalue:postlength forhttpheaderfield:@"content-length"];  // set url [request seturl:requesturl]; 


but point i'm learning on own , difficult understand beginner without explanation i'm asking explanation, detail explanation whole process if have hard time spend on question because believe or not found hardest topic till because main reason there no tutorials whole process , no explanation @ beginners if can step , explain concept it'll easier students learn tomorrow. can explain in detail , how uploading process works , steps reference appreciated.

note : consider have api , key "image" .

here gonna @ image uploading along **parameters because of time upload image along parameters such userid.

  • before going deep our topic let me provide code doing stuff source,all details gonna see below other stack overflow threads , other sites,i'll provide links 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];     (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]];   }     (int = 0; < 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 broad topic have provided documentation link detail info.

    1. we using ** nsmutableurlrequest** instead of ** nsurlrequest** because gonna append data it.if need deep clarification mutable url request go through documentation.
      • sethttpshouldhandlecookies here have decide whether going use cookies or not.to know more visit
      • settimeoutinterval helps set time limit url request.add time interval in seconds after given time,request terminated.
      • sethttpmethod there many methods.but use get , post methods in many cases.difference between post , here , here
    2. boundary helps in separating parameters each other,so server can identify them.the boundary may wish feel free edit it.
    3. here use multipart/form-data; boundary= content type.to know why going content type this thread.
    4. nsmutabledata * body gonna append parameters , values data , later sethttpbody urlrequest.

      • if how call '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 data (i.e body) 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 give data explain going on,all parameters , keys have been append in data here can find more details sending multipart/form.

    1. now add above data request [request sethttpbody:body];
    2. seturl in method add base url of app.
    3. now need make connection server , send request.here use nsurlconnection send request.description nsurlconnection loads data url request , executes handler block on operation queue when request completes or fails.
    4. statuscode helps find out whether got successful response server. if 200 means ok, 500 means internal server error, etc.. more details here .

    5. handle error in else case.

fyi have explained can,refer links better understanding.

edit:

just change name in imageparamater array,to satisfy requirement changed img_one & img_two image.

 - (ibaction)done:(id)sender{      //change input parameters per requirement.      nsdictionary * inputparameters = [nsdictionary dictionarywithobjectsandkeys:                                   @"1",@"user_id" ,                                   "xxx",@"name" ,                                   nil];     nsarray * image = [nsarray arraywithobjects:[uiimage imagenamed:@"test"],nil]; //change test image name     nsarray * imageparameters = [nsarray arraywithobjects:@"image",nil];//added image key.     [self callapiwithparameters:inputparameters images:image imageparamters:imageparameters];               } 

and change point 6 example base url,

//6

 [request seturl:[nsurl urlwithstring:@"http://google.com/files/upload.php?"]]; 

Comments

  1. i'm taking a shot at transferring picture server most recent 2 days there huge amounts of inquiries transferring picture through afnetworking , nsurlsession , different techniques for transferring i'm asking didn't discovered single answer clarifying entire idea how things work , going on under hood looked youtube stuff accessible in quick , trust me no clarification.

    DTI

    ReplyDelete

Post a Comment

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -