I am trying to upload an image with some other variables but I failed. Please tell me where I am doing mistake. I have provided some variables at the top of the code e.g. type , copies and sizing etc . If I post these values to the server without the image parameter It posted successfully But when I try to upload the image with it then it failed. Please watch the code and tell me where I am doing wrong.
`UIImage *img = [UIImage imageNamed:#"java_url.jpg"];
NSData *data = UIImageJPEGRepresentation(img,90);
NSString *md5Hash = [self md5:[NSString stringWithFormat:#"%#",data]];
NSMutableString *postString = [NSMutableString stringWithString:#""];
[postString appendString:[NSString stringWithFormat:#"&%#=%#",#"type", #"8x12" ]];
[postString appendString:[NSString stringWithFormat:#"&%#=%#",#"copies", #"2"]];
[postString appendString:[NSString stringWithFormat:#"&%#=%#",#"sizing", kSizingOptionShrinkToFit]];
[postString appendString:[NSString stringWithFormat:#"&%#=%d",#"priceToUser", 5]];
[postString appendString:[NSString stringWithFormat:#"&%#=%#", #"md5Hash",md5Hash]];
NSString *urlString = [NSString stringWithFormat:#"https://sandbox.pwinty.com/v2/Orders/%#/Photos",OrderId];
NSString *filename = #"facebook_contest_image.png";
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"];
[request addValue:#"72c56256-95a4-44e8-be31-b7b3a0b094b7" forHTTPHeaderField:#"X-Pwinty-MerchantId"];
[request addValue:#"3a1f6f29-d6e1-4f3f-9891-27e5d4f90009" forHTTPHeaderField:#"X-Pwinty-REST-API-Key"];
[request addValue:#"application/x-www-form-urlencoded" 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=\"%#.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:data]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postString appendString:[NSString stringWithFormat:#"&%#=%#", #"file",postbody]];
NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSLog(#"%#",postData);
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);`
I normally use AFNetworking its best library out there for any server requests try this code bellow,
it required AFNetworking
- (void)upload {
// !!! only JPG, PNG not covered! Have to cover PNG as well
NSString *fileName = [NSString stringWithFormat:#"%ld%c%c.jpg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a', arc4random_uniform(26) + 'a'];
// NSLog(#"FileName == %#", fileName);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"lat": #"8.444444",
#"lng": #"50.44444",
#"location": #"New York",
#"type": #"2",
#"claim": #"NYC",
#"flag": #"0"};
// BASIC AUTH (if you need):
manager.securityPolicy.allowInvalidCertificates = YES;
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:#"foo" password:#"bar"];
// BASIC AUTH END
NSString *URLString = #"http://192.168.1.157/tapp/laravel/public/foobar/upload";
/// !!! only jpg, have to cover png as well
NSData *imageData = UIImageJPEGRepresentation(self.imageView.image, 0.5); // image size ca. 50 KB
[manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"file" fileName:fileName mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure %#, %#", error, operation.responseString);
}];
[self dismissViewControllerAnimated:NO completion:nil];
}
Related
I am trying to send a post request.
Here is my try:
-(void)Test{
NSDictionary * orderMasterDict = #{#"distributorId":#10000,
#"fieldUsersId": #3,
#"itemId":#0,#"orderMatserId":#56358 };
Globals.OrderDetailsArray = [NSMutableArray arrayWithObjects:orderDetailsDictAnatomy,orderDetailsDictTexture,orderDetailsDictTranslucency, nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:Globals.OrderDetailsArray options:NSJSONWritingPrettyPrinted error:nil];
NSData *postData2 = [NSJSONSerialization dataWithJSONObject:orderMasterDict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString2 = [[NSString alloc] initWithData:postData2 encoding:NSUTF8StringEncoding];
NSString *jsonString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:jsonString2 forKey:#"orderMaster"];
[_params setObject:jsonString forKey:#"orderDetails"];
[_params setObject:[NSString stringWithFormat:#"3"] forKey:#"userId"];
[_params setObject:[NSString stringWithFormat:#"ALRAISLABS"] forKey:#"subsCode"];
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = #"imageUpload";
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"http://192.168.0.102:8080/Demo/Test/create"];
// 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(_uploadImageView.image, 0.6);
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:[#"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) {
if (error){
NSLog(#"ERROR :",error);
}else{
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"response status code: %ld", (long)[httpResponse statusCode]);
if ([httpResponse statusCode] == 200) {
NSLog(#"StatusCode : %ld",(long)[httpResponse statusCode]);
}else{
NSLog(#"Error");
}
}
}] resume];}
How to make a multipartFormData request?
I tried googling for it, couldn't find any answer suitable for this situation, and thought well .Please help me finding the right solution.
Thanks in advance.
First you change your image in NSData then help of AFNetworking you can post your image.
NSData *data = UIImagePNGRepresentation(yourImage);
imageData = [data base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];
Then use this code:
NSMutableDictionary *finaldictionary = [[NSMutableDictionary alloc] init];
[finaldictionary setObject:imageData forKey:#"image"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST: [NSString stringWithFormat: #"%#%#", IQAPIClientBaseURL, kIQAPIImageUpload] parameters: finaldictionary constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) { }
progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"Success response=%#", responseObject);
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData: responseObject options: NSJSONReadingAllowFragments error: nil];
NSLog(#"%#", responseDict);
}
failure: ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Errorrrrrrr=%#", error.localizedDescription);
}
];
By using Alamofire
-(void)CreateOrder{
NSString * urlString = [NSString stringWithFormat:#"YOUR URL"
NSDictionary * orderMasterDict = #{#"distributorId":stakeholderID,
#"fieldUsersId": userID,
#"itemId":#0,#"orderMatserId":#0 };
Globals.OrderDetailsArray = [NSMutableArray arrayWithObjects:orderDetailsDictAnatomy,orderDetailsDictTexture,orderDetailsDictTranslucency, nil];
NSDictionary * consumerDetails = #{#"consumerName":Globals.PatientName,#"consumerReferenceId":Globals.PatientID,#"notes":Globals.PatientNotes,#"cunsumerContacNumber":#"456464654654"};
NSData *postData = [NSJSONSerialization dataWithJSONObject:Globals.OrderDetailsArray options:NSJSONWritingPrettyPrinted error:nil];
NSData *postData2 = [NSJSONSerialization dataWithJSONObject:orderMasterDict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString2 = [[NSString alloc] initWithData:postData2 encoding:NSUTF8StringEncoding];
NSString *jsonString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
//retrieving userId from UserDefaults
prefs = [NSUserDefaults standardUserDefaults];
NSString * userIdString = [prefs stringForKey:#"userID"];
NSDictionary *parameters = #{#"orderMaster": jsonString2, #"orderDetails" : jsonString ,#"userId" : userIdString,#"subsCode" : #"ABC_MDENT"};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//For adding Multiple images From selected Images array
int i = 0;
for(UIImage *eachImage in selectedImages)
{
UIImage *image = [self scaleImage:eachImage toSize:CGSizeMake(480.0,480.0)];
NSData *imageData = UIImageJPEGRepresentation(image,0.3);
[formData appendPartWithFileData:imageData name:#"imageUpload" fileName:[NSString stringWithFormat:#"file%d.jpg",i ] mimeType:#"image/jpeg"];
i++;
}
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSLog(#"responseObject : %#",responseObject);
if (error) {
NSlog(#"error")
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse statusCode] == 200) {
resposeStatusCode = [responseObject objectForKey:#"statusCode"];
}else{
NSLog(#"requestError");
}
}
}];
[uploadTask resume]; }
I have tried this code to implement multiple images in iOS. Didn't work as I wanted:
NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = #"fileToUpload[]";
NSArray *arrayfile=[NSArray arrayWithObjects:FileParamConstant,FileParamConstant ,nil];
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"http://jackson.amtpl.in/tranzop/api/customertest/postorder"];
// 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]];
}
for (int i=0; i<upload_img_array.count; i++) {
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:[upload_img_array objectAtIndex:0]],1); // add image data
// NSData *imageData = UIImageJPEGRepresentation([upload_img_array objectAtIndex:i], 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image%d.png\"\r\n", FileParamConstant,i] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/png\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]];
}
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set
Use this:
-(void)uploadImages{
// image.finalImage - is image itself
// totalCount - Total number of images need to upload on server
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary *parameters = #{#"Key":#"Value",#"Key":#"Value"};
[manager POST:serverURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(image.finalImage) name:#"ImageName" fileName:[[Helper getRandomString:8] stringByAppendingString:#".png"] mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:kNilOptions error:nil];
_uploadCounter+=1;
if(_uploadCounter<totalCount){
[self uploadImages];
}else {
NSLog(#"Uploading all images done");
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error");
}];
}
This tutorial will help you:
https://charangiri.wordpress.com/2014/09/22/how-to-upload-multiple-image-to-server/
try
//img_send is a UIImage with u want to send
NSData *imageData = UIImagePNGRepresentation(img_send);
str_img= [imageData base64EncodedStringWithOptions:0];
NSDictionary *post_dir = [[NSMutableDictionary alloc] init];
[post_dir setValue:str_img forKey:#"image_string"];
NSData *jsData = [NSJSONSerialization dataWithJSONObject:post_dir options:NSJSONWritingPrettyPrinted error:nil];
NSMutableData *data = [[NSMutableData alloc] init];
self.receivedData = data;
NSURL *url = [NSURL URLWithString:#"YOUR URL STRING"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
//set http method
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsData];
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connection=connection;
//start the connection
[connection start];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"~~~~~ Status code: %d", [response statusCode]);
});
I am trying to upload image with some text data. But When i try it for image upload only. it works! But for param, I am getting result=null. so data is sending null. here is my code.
-(void)uploadImage : (UIImage *)image : (NSString *)url : (NSString *)param
{
NSLog(#"URL : %#", url);
NSLog(#"param : %#", param);
NSData *myData=UIImagePNGRepresentation(image);
NSMutableURLRequest *request;
NSString *urlString = url;
NSString *filename = #"image";
request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSDictionary *temp = #{#"result" : #"rob"
};
//opening boundary
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:#"--%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#.png\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:myData]];
//params
[postbody appendData:[ [temp description] dataUsingEncoding:NSUTF8StringEncoding]];
//closing boundary
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
// conn.delegate = self;
[conn start];
}
may any expert help me what i am missing?
You could use a library like AFNetworking for all your requests. It's very easy and makes your code more readable. Here is a way to create a multipart file upload with parameters (https://github.com/AFNetworking/AFNetworking#creating-an-upload-task-for-a-multi-part-request-with-progress)
NSDictionary *params = #{
#"result" : #"rob"
}
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"http://example.com/upload" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:#"file://path/to/image.jpg"] name:#"file" fileName:#"filename.jpg" mimeType:#"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
I am trying to upload an image from my app to my server. I am following this tutorial (http://zcentric.com/2008/08/29/post-a-uiimage-to-the-web/). When I copy the code from the tutorial I get a bunch of warnings and errors, so I have modified it as below.
The uploadImage method is being called, and twitterImage contains the right photo, but the image is not being uploaded into the user_photos directory. Any recommendations would be great!
Here is my app code:
-(void)uploadImage {
NSData *imageData = UIImageJPEGRepresentation(twitterImage, 90);
NSString *urlString = #"http://website.com/user_photo_upload.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------673864587263478628734";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data;
boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"rn--%#rn",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data;name=\"userfile\";
filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-streamrnrn"
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"rn--%#--rn",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding];
}
Here is my user_photo_upload.php file:
<?php
$uploaddir = '../user_photos/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "http://website.com/user_photos/{$file}";
}
?>
In my suggestion, you can use ASIHTTPRequest framework for image uploading to the server. You can download the framework from here. It is simple easily understandable.
See the below code regarding image uploading using ASIHTTPRequest
NSData *imgData = UIImageJPEGRepresentation(IMAGE, 0.9);
formReq = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlString]];
formReq.delegate = self;
[formReq setPostValue:VAL1 forKey:KEY1];
if (imgData) {
[formReq setData:imgData withFileName:[NSString stringWithFormat:#"ipodfile.jpg"] andContentType:#"image/jpeg" forKey:#"userfile"];
}
[formReq startSynchronous];
You can also refer a nice tutorial here
If you want to move from NSMutableURLRequest then best bet is AFNetworking get it from here
ASIHTTPRequest is not being maintained and should not be used as said by developer of library here
Example oF image upload
-(void)call
{
//the image name is Denise.jpg i have uses image you can youse any file
//just convert it to nsdat in an appropriateway
UIImage *image= [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Denise" ofType:#"jpg"]];
// getting data from image
NSData *photoData= UIImagePNGRepresentation(image);
// making AFHttpClient
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"your url string"]];
//setting headers
[client setDefaultHeader:#"multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY" value:#"Content-Type"];
[client setDefaultHeader:#"key" value:#"value"];
NSMutableURLRequest *request1 = [client multipartFormRequestWithMethod:#"POST" path:#"application/uploadfile" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
//setting body
[formData appendPartWithFormData:[[NSString stringWithFormat:#"Value"] dataUsingEncoding:NSUTF8StringEncoding] name:#"Key"];
[formData appendPartWithFormData:[[NSString stringWithFormat:#"Value"] dataUsingEncoding:NSUTF8StringEncoding] name:#"Key"];
//...
[formData appendPartWithFileData:photoData name:#"file_data" fileName:#"file.png" mimeType:#"image/png"];
}];
[request1 setTimeoutInterval:180];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
// use this float value to set progress bar.
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSLog(#"%#",responseObject);
NSLog(#"response headers: %#", [[operation response] allHeaderFields]);
NSLog(#"response: %#",jsons);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
if([operation.response statusCode] == 403)
{
NSLog(#"Upload Failed");
return;
}
NSLog(#"error: %#", [error debugDescription]);
}];
[operation start];
}
When You are appending the image to body the Content-Disposition should be an attachment not form-data, just before you are appending the image-data on the body. so replace the following code:
[body appendData:[#"Content-Disposition: form-data;name=\"userfile\";
filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
with this:
[body appendData:[#"Content-Disposition: attachment;name=\"userfile\";
filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
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