I\'m working on uploading an image to a server from last two days as there are tons of questions about uploading an image through AFNetworking and NSURLSession and other met
I think it's Helpful 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];
}
here we gonna look at image uploading along with some **parameters because most of time we upload image along with some parameters such as userId.
Before going deep into our topic let me provide the code for doing the stuff source,All the details we gonna see below are from some other stack overflow threads and some from other sites,i'll provide 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 it is a broad topic i have provided documentation link for detail info.
NSMutableData * body we gonna append all the parameters and values to this data and later setHTTPBody to the UrlRequest.
If this is how 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 (i.e 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 give data will clearly explain what going on,all the parameters and keys have been append in the data Here you can find more details about sending multipart/form.
[request setHTTPBody:body];
statusCode which helps to find out whether we got successful response from server. If 200 means OK, 500 means Internal Server Error, etc.. more details here .
Handle the error in else case.
FYI I have explained what i can,refer the links for better understanding.
EDIT:
Just change the name in imageParamater array,To satisfy your requirement changed img_one & img_two with 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 with your example base URL,
//6
[request setURL:[NSURL URLWithString:@"http://google.com/files/upload.php?"]];
Use AFNetworking For this task which will give very easy and reliable solution.