Multipartform Data -Image Uploading - objective-c

I want to uload the image and dictionary to server , i have done something , image is not uploading dictionary is workinfine ,here is my code,
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: dict
options:0
error:nil];
NSString *jsonString =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSDictionary *headers = #{ #"content-type": #"multipart/form-data; boundary=---011000010111000001101001",
#"cache-control": #"no-cache",
#"postman-token": #"f93b7bb9-040f-fa7c-8a65-5a4f8e057cfe" };
NSArray *parameters = #[ #{ #"name": #"userDetails", #"value":jsonString }
,#{ #"name": #"userImage", #"fileName":#{#"0":#{}}}
];
NSString *boundary = #"---011000010111000001101001";
NSError *error;
NSMutableString *body = [NSMutableString string];
for (NSDictionary *param in parameters) {
[body appendFormat:#"--%#\r\n", boundary];
if (param[#"fileName"]) {
[body appendFormat:#"Content-Disposition:form-data; name=\"%#\"; fileName=\"%#\"\r\n", param[#"name"], param[#"fileName"]];
[body appendFormat:#"Content-Type: %#\r\n\r\n", param[#"contentType"]];
[body appendFormat:#"%#", [NSString stringWithContentsOfFile:param[#"fileName"] encoding:NSUTF8StringEncoding error:&error]];
if (error) {
NSLog(#"%#", error);
}
} else {
[body appendFormat:#"Content-Disposition:form-data; name=\"%#\"\r\n\r\n", param[#"name"]];
[body appendFormat:#"%#", param[#"value"]];
}
}
[body appendFormat:#"\r\n--%#--\r\n", boundary];
NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"---.php"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%#", httpResponse);
NSString *stringFromData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",stringFromData);}}];
[dataTask resume];}
i got the msg from server is success,uploaded successfully,but image is not uploaded , i have checked in server ,Please help me to upload the image

Related

NSURLSessionDataTask gives me incorrect token in a Login

I'm updating an iOS app in objective c, and i have the warning sendSynchronousRequest(_:returningResponse:) was deprecated in iOS 9.0: Use [NSURLSession dataTaskWithRequest:completionHandler:]
So I changed my code from:
-(NSString*)getServerResponseByMethod:(NSString*)method clientId:(NSString*)clientId deviceid:(NSString*)deviceid token:(NSString*)token parameters:(NSDictionary*)parameters{
NSString *reponseStr;
NSMutableData *postbody = [NSMutableData data];
Setting *session =[Setting getSessionDataInstance];
NSString *todayDate=[Utils Datefromstring:[NSDate date] byFormatter:#"HH:mm:ss"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/services/?&time=%#", appDelegate.mainUrlString,todayDate]];
NSMutableURLRequest *request=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:600.0];
if([method isEqualToString:#"userLogin"])
{
[postbody appendData:[[NSString stringWithFormat:#"&param=login"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"&username=%#",[parameters objectForKey:#"userName"]] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"&password=%#",[parameters objectForKey:#"password"]] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"&apnstoken=123456789"] dataUsingEncoding:NSUTF8StringEncoding]];
}
if([method isEqualToString:#"userLogout"])
{
[postbody appendData:[[NSString stringWithFormat:#"&param=logOut"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"&user_id=%#",session.userId] dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue:[NSString stringWithFormat:#"%#",session.sessionToken ] forHTTPHeaderField:#"token"];
}
NSString * dataLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postbody length]];
[request addValue:dataLength forHTTPHeaderField:#"Content-Length"];
[ request setHTTPMethod: #"POST" ];
[ request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[ request setHTTPBody: postbody ];
NSLog(#"request===%#",[request allHTTPHeaderFields]);
NSLog(#"URL=====%#",[request URL]);
NSLog(#"request===%#",request);
NSError *theError = nil;
NSURLResponse *urlResponse = nil;
if ([self checkInternet])
{
//THE PART OF THE WARNING ------
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&theError];
if(theError==nil){
reponseStr= [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
NSLog(#"ServerResponse===%#",reponseStr);
}
else{
NSLog(#"sendSynchronousRequest error = %#",theError.localizedDescription);
}
}
else{
reponseStr=#"Network not Available.";
}
return reponseStr;
}
- (BOOL) connectedToNetwork
{
Reachability *r = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [r currentReachabilityStatus];
BOOL internet;
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
internet = NO;
} else {
internet = YES;
}
return internet;
}
-(BOOL) checkInternet
{
//Make sure we have internet connectivity
if([self connectedToNetwork] != YES)
{
return NO;
}
else {
return YES;
}
}
NEW CODE --just adding the parts that modified
-(NSString*)getServerResponseByMethod:(NSString*)method clientId:(NSString*)clientId deviceid:(NSString*)deviceid token:(NSString*)token parameters:(NSDictionary*)parameters
{
__block NSString *reponseStr;
.......
NSString * dataLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postbody length]];
[request addValue:dataLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod: #"POST" ];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPBody: postbody ];
NSLog(#"request===%#",[request allHTTPHeaderFields]);
NSLog(#"URL=====%#",[request URL]);
NSLog(#"request===%#",request);
//NSError *theError = nil;
//NSURLResponse *urlResponse = nil;
if ([self checkInternet])
{
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
if(error==nil)
{
reponseStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"ServerResponse===%#",reponseStr);
}
else
{
NSLog(#"sendSynchronousRequest error = %#",error.localizedDescription);
}
}];
[task resume];
}
else
{
reponseStr=#"Network not Available.";
}
return reponseStr;
}
With this new code, every time I log in displays the message that my username or password is incorrect but with the deprecated method everything works fine.
Any help will be awesome! I've been struggling with this like 3 hours :(
Thanks!
It seems you mixed up between POST or GET in your post body.
Any URL with format
http://abcde.com/what.php?a=1&b=2
is a GET method.
And what you specify is POST method. So make clear about that first.
Secondly, if you are using POST, then the data to post should be formatted
properly (example: https://stackoverflow.com/a/19101084/501439). All the "&"
in your postbody is causing the problem I am sure.

Status code 400 when converting Postman Request into Objective-C

I'm trying to upload an image to an API and then use the result. When using Postman, everything runs successfully. When I used the export feature to convert the code to Objective-C, I tried running it, but I'm getting a status code 400 (my parameters are invalid).
Here is the Postman request:
Here is my own code:
// Get image name
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[refURL] options:nil];
NSString *filename = [[result firstObject] filename];
// Get image file path and append file name onto it
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
[imageData writeToFile:path atomically:YES];
NSDictionary *headers = #{ #"content-type": #"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
#"Content-Type": #"multipart/form-data",
#"Accept": #"application/json",
#"Authorization": #"Token 60f6be2a21bdf731d86a8817b440a1afba692fed",
#"Cache-Control": #"no-cache",
#"Postman-Token": #"7d262730-0c7d-66dc-bbbb-43f40dbfe8ce" };
NSArray *parameters = #[ #{ #"name": #"task", #"value": #"dc9ef71a-b8a0-4a12-90fd-83d717cf887f" },
#{ #"name": #"image_file", #"fileName": path } ];
NSString *boundary = #"----WebKitFormBoundary7MA4YWxkTrZu0gW";
NSError *error;
NSMutableString *body = [NSMutableString string];
for (NSDictionary *param in parameters) {
[body appendFormat:#"--%#\r\n", boundary];
if (param[#"fileName"]) {
[body appendFormat:#"Content-Disposition:form-data; name=\"%#\"; filename=\"%#\"\r\n", param[#"name"], param[#"fileName"]];
[body appendFormat:#"Content-Type: %#\r\n\r\n", param[#"contentType"]];
[body appendFormat:#"%#", [NSString stringWithContentsOfFile:param[#"fileName"] encoding:NSASCIIStringEncoding error:&error]];
if (error) {
NSLog(#"%#", error);
}
} else {
[body appendFormat:#"Content-Disposition:form-data; name=\"%#\"\r\n\r\n", param[#"name"]];
[body appendFormat:#"%#", param[#"value"]];
}
}
[body appendFormat:#"\r\n--%#--\r\n", boundary];
NSData *postData = [body dataUsingEncoding:NSASCIIStringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://api.vize.ai/v1/classify/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%#", httpResponse);
}
}];
[dataTask resume];
(It's not shown here, but I'm trying to use an image that the user will select from an image picker.) Why am I getting a status code 400 and how can I get the correct result?

Posting an image with parameters - AFNetworking 3.1 and objective c (Xcode 8)

I am looking for some leads to my problem.
I have practically looked through all links related to posting/uploading an image to a server, but nothing seems to make my code work.
I have posted 2 options... in different ways... the commented code indicates that... my request goes blank to the server.
I have tried using different options - appendPartWithFormData, appendPartWithFileData.
OPTION 1
NSError* error;
// Create paths to output images
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Test.png"];
UIImage *image = [UIImage imageWithData:self.imageData];
[UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];
NSURL *imagePath = [NSURL fileURLWithPath:pngPath];
NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:[requestParameter valueForKey:#"Param"] options:0 error:&error];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];
NSLog(#"converted JOSN Data %#",jsonInputString);
NSDictionary* params = #{#"request": jsonInputString };
[manager POST:[requestParameter valueForKey:#"methodName"] parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
//[formData appendPartWithFormData:self.imageData name:#"profilepic" ];
//[formData appendPartWithFileData:self.imageData name:#"profilepic" fileName:#"profilepic.png" mimeType:#"image/png"];
[formData appendPartWithFormData:jsonInputData name:#"request"];
[formData appendPartWithFileURL:[NSURL fileURLWithPath:pngPath]
name:#"File"
error:nil];
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Success: %#", responseObject);
[self requestSuccessed:responseObject];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
[self requestFailed:error];
}];
OPTION 2
NSError* error;
NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:[requestParameter valueForKey:#"Param"] options:0 error:&error];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];
NSDictionary* params = #{#"request": jsonInputString };
AFURLSessionManager *manager1 = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:[NSString stringWithFormat:#“XXXXXXX”] parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:#"timeoutInterval"] longValue];
// [req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [req setHTTPBody:[jsonInputString dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"profile_pic\"; filename=\"pic.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:self.imageData];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[req addValue:contentType forHTTPHeaderField: #"Content-Type"];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"request\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:jsonInputString] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPBody:body];
[[manager1 dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(#"Reply JSON: %#", responseObject);
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(#"Error: %#, %#, %#", error, response, responseObject);
}
}] resume];
This usually works for me. You need to make sure your RESTful script pick up the correct file handle. I don't know Java, but in PHP I would do it as: $image = $_FILES["imagename"]["name"];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSLog(#"Saving image file");
[formData appendPartWithFileData:UIImagePNGRepresentation(image) name:#"imagename" fileName:#"image.png" mimeType:#"image/png"];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"JSON uploadProgress.fractionCompleted: %f", uploadProgress.fractionCompleted);
});
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
//NSLog(#"Error: %#", error);
NSLog(#"RESPONSE: %# %#", response, responseObject);
if(error) {
NSLog(#"Error: %#", error);
} else {
NSString *responseString = [[[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding] mutableCopy];
NSLog(#"RESPONSE: %#", responseString);
}
}];
[uploadTask resume];
Try this one, hopefully it will solve your problem
// your parametes here
userInfoDict=[[NSMutableDictionary alloc] init];
[userInfoDict setValue:#"image" forKey:#"iamge"];
// if image is too large than the timeout intervel
// [_request setTimeoutInterval:1000];
_request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"api url" parameters:userInfoDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
//convert imahe into data
NSData* data = UIImagePNGRepresentation(yourImage);
[formData appendPartWithFileData:data name:#"api paramets name in which you want to post image" fileName:#"myImage.png" mimeType:#"image/png"];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
_uploadTask = [manager
uploadTaskWithStreamedRequest:_request
progress:^(NSProgress * _Nonnull uploadProgress)
{
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[_playerProgress setProgress:uploadProgress.fractionCompleted];
NSLog(#"\n uploading image vlaues %f\n",uploadProgress.fractionCompleted);
// for uploading video in background
manager.attemptsToRecreateUploadTasksForBackgroundSessions=YES;
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
// [_playerProgress setHidden:YES];
} else
{
NSLog(#"%# ", response);
// after upload comnlete disablle background uploading
manager.attemptsToRecreateUploadTasksForBackgroundSessions=NO;
NSLog(#"\n\n REsponse Form Server %#\n\n",responseObject);
//[responseObject valueForKey:#"error"];
//remove temp file
NSError *error;
}
}
];
[_uploadTask resume];

Post data on web server with web service

Hello I am tying to save data on web server with a web service implemented in PHP.
I am trying below code to do it. I am getting response from server but the data is not getting saved to server. I have wasted 5-6 hours of the day in googling and trying code given on net. But nothing seems to work :(
NSDictionary *someInfo = [NSDictionary dictionaryWithObjectsAndKeys:
txtTreasureName.text, #"name",
txtDescription.text, #"description",
txtMaterials.text, #"materials",
#"77.3833", #"longitude",
#"29.0167", #"latitude",
categoryIdStr, #"categoryId",
nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:treasureInfo
options:NSJSONWritingPrettyPrinted
error:&error];
if (! jsonData) {
DLog(#"Got an error: %#", error);
} else {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *urlString = #"http://www.myurl.php";
NSURL *url = [NSURL URLWithString:urlString];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json"
forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json"
forHTTPHeaderField:#"Accept"];
[request setValue:[NSString stringWithFormat:#"%d",
[jsonData length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:jsonData];
DLog(#"%#", request);
[[NSURLConnection alloc]
initWithRequest:request
delegate:self];
// Print json
DLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *error) {
if ([data length] &&
error == nil) {
DLog(#"%#", [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]);
if ([self shouldDismiss]) {
[self dismissViewControllerAnimated:YES
completion:nil];
}
}
}];
}
Set Request URL in the function,
You have alread y created data Dictionary
NSDictionary *someInfo = [NSDictionary dictionaryWithObjectsAndKeys:
txtTreasureName.text, #"name",
txtDescription.text, #"description",
txtMaterials.text, #"materials",
#"77.3833", #"longitude",
#"29.0167", #"latitude",
categoryIdStr, #"categoryId",
nil];
Add this function to your implementation file and invoke it, rest will be dont by this function
[self postWith:someInfo];
Add this
- (void)postWith:(NSDictionary *)post_vars
{
#warning Add your Webservice URL here
NSString *urlString = [NSString stringWithFormat:#"YourHostString"];
NSURL *url = [NSURL URLWithString:urlString];
NSString *boundary = #"----1010101010";
// define content type and add Body Boundry
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSEnumerator *enumerator = [post_vars keyEnumerator];
NSString *key;
NSString *value;
NSString *content_disposition;
while ((key = (NSString *)[enumerator nextObject])) {
value = (NSString *)[post_vars objectForKey:key];
content_disposition = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key];
[body appendData:[content_disposition dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close the request body with Boundry
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%d", body.length] forHTTPHeaderField: #"Content-Length"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}

Upload A File Into A Server - Objective C/Xcode/Mediawiki

I want to upload a UIImage into a server. For this I am using the following lines of code ::
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
imageView.image = image;
NSData *pngData = UIImagePNGRepresentation(imageView.image);
NSString *imageFile = #"image.png";
NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [docDir stringByAppendingPathComponent:imageFile];
NSString *dataIS=[NSString base64StringFromData:pngData length:[pngData length]];
[pngData writeToFile:filePath atomically:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------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:#"Content-Disposition: form-data; name=\"image\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:pngData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
[self.parentViewController dismissModalViewControllerAnimated:YES];
}
But, I am getting the following error in gdb ::
Your request could not be processed. Request could not be handled.
I am also confused over the proper use of urlString i.e. I am doubtful over my correct use of it.
If I however use the following urlString, I am able to upload my image file into the server ::
NSString *urlString = [NSString stringWithFormat:#"http://xxxx.com/mediawiki/api.php?action=upload&filename=image.png&url=%#&token=%#", url, token] ;
With reference to the API for mediawiki (http://www.mediawiki.org/wiki/API:Upload), can someone help me to sort it out ?? Thanks and Regards.
I have same problem to upload multiple images and data but i am use AFNetworking class and Upload multiple images into server.
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"your URL"]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
path = [[NSString alloc] initWithString:[URL absoluteString]];
vdict = #{
// Your Parameter Pass
};
[self checkmultiple:vdict];
-(void)checkmultiple:(NSDictionary*)vdict
{
AFHTTPRequestOperation *op = [manager POST:path parameters:vdict constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
for(i = 0;i<[appDelegate.gblarrydata count];i++)
{
NSString *paths = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"New Folder"];
// NSLog(#"%#",paths);
NSString *documentsDirectory = paths;
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[[appDelegate.gblarrydata objectAtIndex:i]valueForKey:#"nameimage"]];
NSData *data1 =[[NSData alloc]initWithContentsOfFile:getImagePath];
NSString *data2 =[[appDelegate.gblarrydata objectAtIndex:i] valueForKey:#"Note"];
[formData appendPartWithFileData:data1 name:[NSString stringWithFormat:#"pimage%d",i+1] fileName:[NSString stringWithFormat:#"pimage%d.jpg",i+1] mimeType:#"image/jpeg"];
if(![data2 isEqualToString:#""])
{
[formData appendPartWithFormData:[data2 dataUsingEncoding:NSUTF8StringEncoding]
name:[NSString stringWithFormat:#"pnotes%d",i+1]];
}
}
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Upload success");
NSString *returnString = [NSString stringWithFormat:#"%#",[responseObject JSONRepresentation]];
NSLog(#"Reg Date:%#",returnString);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error:%#",error);
}];
[op start];
}
I had the same problem. I used ASIHTTPRequest, for uploading files, it works fine.
Uploading:
Imagefile:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:#"Ben" forKey:#"names"];
[request addPostValue:#"George" forKey:#"names"];
[request addFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photos"];
[request addData:imageData withFileName:#"george.jpg" andContentType:#"image/jpeg" forKey:#"photos"];
With Other data simultaneously:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
// Upload a file on disk
[request setFile:#"/Users/ben/Desktop/ben.jpg" withFileName:#"myphoto.jpg" andContentType:#"image/jpeg"
forKey:#"photo"];
// Upload an NSData instance
[request setData:imageData withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"photo"];
for Downloading to desired Path:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:#"/Users/ben/Desktop/my_file.txt"];
If you want to send image to server,send by data in encoded form,server can handle encoded form of image and they will get image data in encoded from.
// UIImage * img = [UIImage imageNamed:#"min.png"];
// NSData *imageData = UIImageJPEGRepresentation(img,0.2);
NSString *strUrl =[NSString stringWithFormat:#"%#/upload_file.php", [globalApp sharedUser].vg_dominio ];
//strUrl = #"http://192.168.1.100/mismedicinas/upload_file.php";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl]];
request.HTTPMethod = #"POST";
request.timeoutInterval = 60;
request.HTTPShouldHandleCookies = false;
//[request setHTTPMethod:#"POST"];
NSString *boundary = #"----------SwIfTeRhTtPrEqUeStBoUnDaRy";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
//[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSMutableData *tempData = [NSMutableData data];
[tempData appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[tempData appendData:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\"iphoneimage.xml\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[tempData appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//[tempData appendData:[NSData dataWithData:imageData]]; ///IMAGEN
[tempData appendData:[NSData dataWithData:cData]];
[tempData appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData: tempData];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue: [NSString stringWithFormat:#"%d", body.length ] forHTTPHeaderField:#"Content-Length"];
request.HTTPBody =body;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"finalizacion %#", returnString);