Image not posting by base64 string on json - ios

I am Posting a image on Server By json Post Webservice.I have to upload the image on base 64 .I am encoding my image to base 64 string but the Image is not posting on the server and not other things.There is No problem with the webservice.The image is uploading successfully in android.
selectedImage=[[NSData alloc]initWithData:UIImageJPEGRepresentation(image, 1.0)];
[[NSUserDefaults standardUserDefaults]setObject:selectedImage forKey:#"image"];
[[NSUserDefaults standardUserDefaults]synchronize];
strImage=[[NSString alloc]init];
strImage = [selectedImage base64Encoding];
strImage=[strImage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"strImage %#",strImage);
/*
NSData *b64DecData = [Base64 decode:strImage];
NSLog(#"strImage %#",strImage);
[bttnimage setBackgroundImage:[UIImage imageWithData:b64DecData] forState:UIControlStateNormal];
*/
NSString *post=[[NSString alloc]initWithFormat:#"name=%#&aboutMe=%#&chatId=%#&gender=%#&lookingFor=%#&city=%#&birthdate=%#&anniversarydate=%#&number1=%#&number2=%#&number3=%#&image=%#",[txtProfileName.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[txtComment.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[appDelegate.chatid stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[bttnGender.titleLabel.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[bttnLookingfor.titleLabel.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[txtPlace.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[dobLabel.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[anniversaeyLabel.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[txtNumber.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[txtNum1.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[txtNum2.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],strImage];
NSLog(#"post %#",post);
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *latrequest = [[NSMutableURLRequest alloc] init];
NSString *url=[NSString stringWithFormat:#"http://www.xyzAbc.org/iphone/updateProfile.php?%#",post];
NSLog(#"url %#",url);
[latrequest setURL:[NSURL URLWithString:url]];
Connection=[NSURLConnection connectionWithRequest:latrequest delegate:self];
[latrequest setHTTPMethod:#"POST"];
[latrequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[latrequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[latrequest setHTTPBody:postData];
[latrequest release];
NSLog(#"latre %#",latrequest);
the code is above Please Let me know if I am missing something. Please any one Help me with that.

First add Base64.h and Base64.m files to your project. The following method will return Base-64 string from UIImage.
-(NSString*)getBase64StringfromImage:(UIImage*)image{
NSData *imageData = UIImageJPEGRepresentation(image,90);
NSString *ImgStr=[Base64 encode:imageData];
ImgStr=[ImgStr stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
return ImgStr;
}

Image posting is different in iOS when we compare it with Android.
And in iOS do this formate
NSString *urlString = [NSString stringWithFormat:#"********************/web-services/register_user.php?firstname=%#&lastname=%#&email=%#&password=%#&location=india&device=IPHONE",details.fname,details.lname,details.emailAddress,details.password];
// urlString=[urlString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
UIImage *image=details.pic;
NSData *imageData =UIImageJPEGRepresentation(image, 0.1);
double my_time = [[NSDate date] timeIntervalSince1970];
NSString *imageName = [NSString stringWithFormat:#"%d",(int)(my_time)];
NSString *string = [NSString stringWithFormat:#"%#%#%#", #"Content-Disposition: form-data; name=\"profile_pic\"; filename=\"", imageName, #".jpg\"\r\n\""];
NSMutableURLRequest *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]];
[body appendData:[[NSString stringWithString:string] 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*s11= [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *responseDictionary1;
responseDictionary1 = [XMLReader dictionaryForXMLString:s11 error:nil];
////////
This will fix issue
Regards
Charan Giri

Related

How can I send an email with attachement using the API MailJet in iOS programmatically?

FIRST ERROR
I use this code but I don't know how to use the api Mailjet in iOS ? Where to put the API key private, the public etc...
I check the github mailjet, the doc mailJet about the API without success.
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSLog(#"File Size: %lu",(unsigned long)[data length]);
//set up request
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://api.mailjet.com/v3/send"]];
[request setHTTPMethod:#"POST"];
//required xtra info
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//body of the post
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"thefile\"; filename=\"recording\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[#"Content-Type: application/octet-stream\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSURLConnection *apiConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
I do tests with sending "manually", and I have that bad answer. Where I have to put the API KEY and the SECRET KEY ?
EDIT
SECOND ERROR
New code :
NSString *apiKey = #"*******************";
NSString *secretKey = #"**************";
NSString *mail = #"******#******.***";
// 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:#"1.0" forKey:#"ver"];
[_params setObject:#"en" forKey:#"lan"];
[_params setObject:apiKey forKey:#"apiKey"];
[_params setObject:secretKey forKey:#"secretKey"];
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = #"----------***********";
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = #"file";
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"https://api.mailjet.com/v3/send/"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
//HTTP Basic Authentication
NSString *authenticationString = [NSString stringWithFormat:#"%#:%#", apiKey, secretKey];
NSData *authenticationData = [authenticationString dataUsingEncoding:NSASCIIStringEncoding];
NSString *authenticationValue = [authenticationData base64Encoding];
[request setValue:[NSString stringWithFormat:#"Basic %#", authenticationValue] forHTTPHeaderField:#"Authorization"];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"#"application/json"; boundary=%#", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
[request addValue:apiKey forHTTPHeaderField:#"apiKey"] ;
[request addValue:secretKey forHTTPHeaderField:#"secretKey"] ;
// post bodyv
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
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; FromEmail:\"contact#****.fr\"; \"Text-part\":\"Dear\" ; Recipients:[{\"Email\":\"****#gmail.com\"}]; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"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:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#, error: %#", requestReply, error);
}] resume];
New error message:
Any ideas?
Here is the code:
- (void) sendToMail:(NSString *)mailingList
{
NSString *filePath = [[self documentsDirectory] stringByAppendingPathComponent:STATS_FILE];
NSFileManager *fileManager = [NSFileManager defaultManager];
mailingList = MAILING_LIST;
if ([fileManager fileExistsAtPath:filePath])
{
// 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:#"xxxx#xxxx.xxx" forKey:#"FromEmail"];
[_params setObject:#"xxx xxx xxxx" forKey:#"FromName"];
[_params setObject:#"xxx xxx xxx" forKey:#"Subject"];
[_params setObject:#"xxx xxxx xxxx" forKey:#"Html-part"];
//mail(s) treatment
NSUInteger numberOfOccurrences = [[mailingList componentsSeparatedByString:#";"] count] - 1;
NSArray *subStrings = [mailingList componentsSeparatedByString:#";"];
NSMutableArray *mailsArr = [NSMutableArray new];
for (int i=0; i<=numberOfOccurrences; i++)
{
NSString *mail = [subStrings objectAtIndex:i];
if ([self validEmail:mail])
[mailsArr addObject:#{#"Email":mail}];
}
if ([mailsArr count] > 0)
[_params setObject:mailsArr forKey:#"Recipients"];
//add any attachment file to JSON
NSData* data = [NSData dataWithContentsOfFile:filePath];
if (data)
{
NSString *encodedString = [data base64EncodedStringWithOptions:0];
NSArray *attachmentsArr = #[#{#"Content-type":#"text/plain", #"Filename":[NSString stringWithFormat:#"%#.db", [[[UIDevice currentDevice] identifierForVendor] UUIDString]], #"content":encodedString}];
[_params setObject:attachmentsArr forKey:#"Attachments"];
}
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"https://api.mailjet.com/v3/send/"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
//HTTP Basic Authentication
NSString *authenticationString = [NSString stringWithFormat:#"%#:%#", API_KEY, SECRET_KEY];
NSData *authenticationData = [authenticationString dataUsingEncoding:NSASCIIStringEncoding];
NSString *authenticationValue = [authenticationData base64EncodedStringWithOptions:0];
[request setValue:[NSString stringWithFormat:#"Basic %#", authenticationValue] forHTTPHeaderField:#"Authorization"];
NSString *jsonRequest = [_params JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSMutableData *requestData = [[jsonRequest dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// setting the body of the post to the request
[request setHTTPBody:requestData];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[requestData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setURL:requestURL]; // set URL
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
#if DEBUG
NSLog(#"requestReply: %#, error: %#", requestReply, error);
#endif
if (error == nil)
{
[self showAlertWithMessage:#"File sent!" withButton:#"Ok!"];
}
else
{
[self showAlertWithMessage:#"Could not send file!" withButton:#"Ok!"];
}
}] resume];
}
I'm leading the API at Mailjet.
Few things to note in your post:
It seems your call lacks a Basic Authentification, see Postman documentation for more details on about to set it. You can fetch your API credentials here
You use a form-data Content-Type while our API only supports application/json as input format. Please refer to our API guides for more details about the payload to send us
You do not seem to provide your API credentials in the objective-c code you provided. Same than in the first point, you can fetch them from here
We do not officially support iOS with Objective-C or Swift, apologies for the inconvenience.
Hope it helps
Thanks for having chosen Mailjet to power your emails!

How to upload video with Privacy setting unlisted in Youtube

I am uploading video on youtube using this code..
- (void)sendVideoFileMetadata:(NSDictionary *)videoMetadata
error:(NSError **)error
{
[self logDebug:#"Sending file info..."];
NSString *category = videoMetadata[kDDYouTubeVideoMetadataCategoryKey];
NSString *keywords = videoMetadata[kDDYouTubeVideoMetadataKeywordsKey];
NSString *title = videoMetadata[kDDYouTubeVideoMetadataTitleKey];
NSString *desc = videoMetadata[kDDYouTubeVideoMetadataDescriptionKey];
NSString *xml = [NSString stringWithFormat:
#"<?xml version=\"1.0\"?>"
#"<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">"
#"<media:group>"
#"<media:title type=\"plain\">%#</media:title>"
#"<media:description type=\"plain\">%#</media:description>"
#"<media:category scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">%#</media:category>"
#"<media:keywords>%#</media:keywords>"
#"<media:privacyStatus>unlisted</media:privacyStatus>"
#"</media:group>"
#"</entry>", title, desc, category, keywords];
NSURL *url = [NSURL URLWithString:#"https://gdata.youtube.com/action/GetUploadToken"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"GoogleLogin auth=\"%#\"", self.authorizationToken] forHTTPHeaderField:#"Authorization"];
[request setValue:#"2" forHTTPHeaderField:#"GData-Version"];
[request setValue:#"unlisted" forHTTPHeaderField:#"privacyStatus"];
[request setValue:[NSString stringWithFormat:#"key=%#", self.developerKey] forHTTPHeaderField:#"X-GData-Key"];
[request setValue:#"application/atom+xml; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%u", (unsigned int)xml.length] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:[xml dataUsingEncoding:NSUTF8StringEncoding]];
self.responseData = [[NSMutableData alloc] init];
self.currentConnection = [DDURLConnection connectionWithRequest:request delegate:self];
[self.currentConnection setType:DDYouTubeUploaderConnectionTypePrepare];
// Create error if there were
// problems creating a connection
if (!self.currentConnection)
{
*error = [self createErrorWithCode:DDYouTubeUploaderErrorCodeCannotCreateConnection
description:#"Cannot create connection to YouTube."];
}
}
- (BOOL)uploadVideoFile:(NSURL *)fileURL
error:(NSError **)error
{
NSString *boundary = #"AbyRvAlG";
NSString *nextURL = #"http://www.youtube.com";
NSData *fileData = [NSData dataWithContentsOfFile:[fileURL relativePath]];
_videoFileLength = [fileData length];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#?nexturl=%#", self.uploadURLString, nextURL]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary] forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSMutableString *bodyString = [NSMutableString new];
// Add token
[bodyString appendFormat:#"\r\n--%#\r\n", boundary];
[bodyString appendString:#"Content-Disposition: form-data; name=\"token\"\r\n"];
[bodyString appendString:#"Content-Type: text/plain\r\n\r\n"];
[bodyString appendFormat:#"%#", self.uploadToken];
// Add file name
[bodyString appendFormat:#"\r\n--%#\r\n", boundary];
[bodyString appendFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#\"\r\n", [fileURL lastPathComponent]];
[bodyString appendFormat:#"Content-Type: application/octet-stream\r\n\r\n"];
[bodyString appendFormat:#"privacyStatus: unlisted\r\n\r\n"];
// Create the data
[body appendData:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:fileData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// Set the body
[request setHTTPBody:body];
// Create the connection
self.responseData = [[NSMutableData alloc] init];
self.currentConnection = [DDURLConnection connectionWithRequest:request delegate:self];
[self.currentConnection setType:DDYouTubeUploaderConnectionTypeUpload];
if (!self.currentConnection)
{
*error = [self createErrorWithCode:DDYouTubeUploaderErrorCodeCannotCreateConnection
description:#"Cannot create connection to YouTube."];
return NO;
}
return YES;
}
This working perfectly,
But the issue is video uploaded as Public, i want to upload it as Unlisted.
I have tried so many tag but not able to get success.
Used,
- privacy
- privacystatus
Can anyone let me know where should i add the tag and whats the tag?
Code snippet will be more helpful.
Just update xml by adding
<yt.accesscontrol>
and it will uplaoad video as unlisted
NSString *xml = [NSString stringWithFormat:
#"<?xml version=\"1.0\"?>"
#"<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">"
#"<media:group>"
#"<media:title type=\"plain\">%#</media:title>"
#"<media:description type=\"plain\">%#</media:description>"
#"<media:category scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">%#</media:category>"
#"<media:keywords>%#</media:keywords>"
#"</media:group>"
#"<yt:accessControl action='list' permission='denied'/>"
#"</entry>", title, desc, category, keywords];

How to pass the image on json server and convert that image into string and pass it into URL?

I try to pass the image on json and store on it but it couldn't pass on that server. i have make code for that so how to pass that image on json and how to convert that image into string and store on json.
NSString *urlSTR = [NSString stringWithFormat:#"http://IOSAPI/registration.php?Profile_Picture&User_Name=%#&First_Name=%#&Last_Name=%#&Email_ID=%#&Password=%#",_textFieldUserName.text,_textFieldFirstName.text,_textFieldLastName.text,_textFieldEmail.text,_textFieldPassward.text];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlSTR] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0];
NSURLResponse *responce;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&responce error:nil];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"RESPONCE %#",dictionary);
NSLog(#"RESPONCE %#",[dictionary valueForKey:#"status"]);
NSString *str = [NSString stringWithFormat:#"%#", [dictionary valueForKey:#"status" ]];
UIImage *images=self.imageView2.image;
NSData *imageData =UIImageJPEGRepresentation(images, 0.1);
double my_time = [[NSDate date] timeIntervalSince1970];
NSString *imageName = [NSString stringWithFormat:#"%d",(int)(my_time)];
NSString *string = [NSString stringWithFormat:#"%#%#%#", #"Content-Disposition: form-data; name=\"picture\"; filename=\"", imageName, #".jpg\"\r\n\""];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlSTR]];
[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]];
[body appendData:[[NSString stringWithString:string] 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*s11= [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#",s11);
NSString *string = [NSString stringWithFormat:#"%#%#%#", #"Content-Disposition: form-data; name=\"profile_pic\"; filename=\"", imageName, #".jpg\"\r\n\""];
NSData *data = UIImageJPEGRepresentation(images, 1.0);
NSString *StrCoverImageData = [data base64EncodedStringWithOptions:0];
use this string to send over server.

how to upload multiple images to server ios?

I am trying to upload Image From my IOS device to server. when upload single image file to server it is successfully uploaded to my server. i want to upload multiple image files to server how can i do this.
// COnvert Image to NSData
NSData *dataImage = UIImageJPEGRepresentation([UIImage imageNamed:#"icon.png"], 1.0f);
// set your URL Where to Upload Image
NSString *urlString = #"http://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/imgupload.php";
// set your Image Name
NSString *filename = #"icon";
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableURLRequest* 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 *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.png\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
// Get Response of Your Request
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
Muliple images upload attempted code
-(void)uploadImageToServer:(NSArray*)arrUploadData withTreatmentDetails:(NSDictionary *)dictArguments url:(NSString*)url
{
// COnvert Image to NSData
// set your URL Where to Upload Image
NSString *urlString = #"http://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/imgupload.php";
// set your Image Name
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableURLRequest* 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 *postbody = [NSMutableData data];
for (int i=0; i<[arrUploadData count]; i++)
{
NSData *dataImage = [[arrUploadData objectAtIndex:i] valueForKey:#"photographyData"];
NSString *filename = [[arrUploadData objectAtIndex:i] valueForKey:#"photographyimagename"];
if (dataImage)
{
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.png\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
}
Hello, You can do it by using NSMutableArray
For Example :
NSMutableArray *arrayImageData = [[NSMutableArray alloc]init];
Take images from imagepicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
NSString *filePath,*path;
NSData *dataImage = UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],1);
[arrayImageData addObject:dataImage];
filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"screenShot1.png"];
[picker dismissViewControllerAnimated:YES completion:nil];
}
At the time of posting image on Server use following code
for (int i = 0; i < [arrayImageData count]; i++)
{
[request setPostValue:[[MYUtility getInstance] base64StringFromNSData:[arrayImageData objectAtIndex:i]] forKey:[NSString stringWithFormat:#"Image%d", i + 1]];
}
Hope this will help for you...I used this code for saving multiple images on server.

Form Data Request using NSURLConnection in iOS

I want to make http form post using NSURLConnection in iOS. I have two form fields and one file upload option in an HTML form. When I am doing same thing using NSURLConnection I am not getting a response.
NSString *urlString = #"http://url/test.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"file\"; filename=\"myphoto.png\"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-streamrnrn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:filedata];
[body appendData:[[NSString stringWithFormat:#"&s=YL4e6ouKirNDgCk0xV2HKixt&hw=141246514ytdjadh"] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"RETURNED:%#",returnString);
But when I use ASIHTTPRequest and write the following code it's working and I am getting a response.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://url/test.php"]];
[request setPostValue:#"YL4e6ouKirNDgCk0xV2HKixt&hw" forKey:#"ssf"];
[request setPostValue:#"141246514ytdjadh" forKey:#"sds"];
[request setData:filedata withFileName:#"myphoto.png" andContentType:#"image/jpeg" forKey:#"file"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(#"response:%#",response);
}
Can anyone tell me what I'm doing wrong with the NSURLConnection part?
You are not copying the example of that link. In that tutorial, the HTTPBody parameter is supposed to be an instance of NSData, not NSString.
[request setHTTPMethod:#"POST"];
NSString *myString = [NSString stringWithFormat:#"value1=test3&value2=test"];
[request setHTTPBody:[myString dataUsingEncoding:NSUTF8StringEncoding]];
I tried this code for uploading the image and its working. Added boundry.
NSString *urlString = #"URL";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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]];
[body appendData:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\"Test.png\"\r\n" 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];
This is working fine for me.
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableURLRequest *req=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"http:///URL/iinsert.php"]];
NSString *myreqstr=#"name=abhii&address=knrr";
NSData *myreqdata=[NSData dataWithBytes:[myreqstr UTF8String] length:[myreqstr length]];
[req setHTTPMethod:#"POST"];
[ req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[ req setHTTPBody: myreqdata ];
//[req setValue:#"abhii" forHTTPHeaderField:#"name"];
//[req setValue:#"kar" forHTTPHeaderField:#"address"];
NSData *data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSLog(#"%#",data);
NSString *returnstring=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",returnstring);
// Do any additional setup after loading the view, typically from a nib.
}
Try this ....
NSURL *url = [NSURL URLWithString:#"URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *myRequestString =#"Request string";
NSLog(#"%#",myRequestString);
NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ];
[ request setHTTPBody: myRequestData ];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
You have several
rn
in the end of your strings. All of them should be
\r\n
More precisely it should be:
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"file\"; filename=\"myphoto.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

Resources