upload image from iPhone application - iphone

i am trying to upload a image to server from iPhone application
PHP code for upload image is following
if(isset($_POST['insertImage']))
{ //INSERT IMAGE -------------------
$method=safeData($_POST['insertImage']);
if($method=='true')
{
if(isset($_POST['userId']))
{
if(isset($_FILES['imageFile']))
{
if($_FILES['imageFile']['type']=="image/gif" || $_FILES['imageFile']['type']=="image/bmp" || $_FILES['imageFile']['type']=='image/jpeg' || $_FILES['imageFile']['type']=='image/jpg' || $_FILES['imageFile']['type']=='image/png')
{
if($_FILES['imageFile']['size']<=5250000)
{
$userId=safeData($_POST['userId']);
$newImgName=rand()."a".time().".".findexts($_FILES["imageFile"]["name"]); imgPath="./../admin/images/";
move_uploaded_file($_FILES['imageFile']['tmp_name'],$imgPath.$newImgName);
$data.=saveImageInfo($userId,$newImgName);
}
else
{
$data.="<List><ResponseCode>405</ResponseCode><Message>Maximum image size should not be more than 5mb </List>";
}
}
else
{
$data.="<List><ResponseCode>405</ResponseCode><Message>Invalid image format. only png,jpg,bmp formats supported</Message></List>"; }
}
else
{
$data.="<List><ResponseCode>405</ResponseCode><Message>imageFile method not found</Message></List>";
}
}
else
{
$data.="<List><ResponseCode>405</ResponseCode><Message>userId method not found</Message></List>";
}
}
else
{
$data.="<List><ResponseCode>405</ResponseCode><Message>invalid insertImage argument</Message></List>";
}
}
and I used following code to upload image to server
+(NSData *)setUserImage:(NSData *)userImageData UserId:(int)UserId
{
NSString *result;
NSData *responseData;
#try {
NSURL *url = [[NSURL alloc] initWithString:webAddress];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
[req setHTTPMethod:#"POST"];
[req setValue:#"multipart/form-data; boundary=*****" forHTTPHeaderField:#"Content-Type"];//
NSMutableData *postBody = [NSMutableData data];
NSString *stringBoundary = [NSString stringWithString:#"*****"];
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"insertImage\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"true"] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"userId\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"%d",UserId] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"imageFile\"; filename=\"myimagefile.png\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
//[postBody appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"imageFile\"; filename=\"myimagefile.png\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[NSData dataWithData:userImageData]];// dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[req setHTTPBody: postBody];//putParams];
NSHTTPURLResponse* response = nil;
NSError* error = [[[NSError alloc] init] autorelease];
responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if(isInDebugMode)
NSLog(#"Result: %#", result);
[url release];
[req release];
IceCreamManFinderAppDelegate *delegate1=(IceCreamManFinderAppDelegate *)[UIApplication sharedApplication].delegate;
if(error.domain!=nil)
{
NSString *errorDesc=[[error userInfo] objectForKey:#"NSLocalizedDescription"];
delegate1.globalErrorMessage=errorDesc;
return nil;
}
else
{
delegate1.globalErrorMessage=nil;
}
}
#catch (NSException* ex) {
NSLog(#"Error: %#",ex);
}
return responseData;
}
from above code i get following response from server
Invalid image format. only png,jpg,bmp formats
i tried lot but not success.
Please suggest where i am wrong?

You wrote the server code to only accept data with certain specified content types, but then you never added the content type to your data. Simply emit the correct content type for your image data:
// Emit the content type here as well
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"imageFile\"; filename=\"myimagefile.png\"\r\nContent-Type: image/png\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[NSData dataWithData:userImageData]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
The error is actually coming back from your own server response, so simply following the flow of control on your server code gives you the cause.

Related

How to upload parameters along with image and audio in iphone

I am new to iPhone programming. Can any body tell me I have upload image and audio along with these parameters
Input Parameters: caption, user_id, mobile_tauky_id, blauky_id, image, audio (caption and blauky_id are optional)
Using below code i can upload image, similarly I want to upload first caption, user_id means some integer value ex: 3, mobile_tauky_id also some integer value ex: 5, blauky_id also ex: 2, image and audio.
Where can I append these parameters First I want append Caption, next user_id, then mobile_tauky_id, blauky_id, after that i have to append image and audio. Can any body tell me how can I append these parameters in below code. I can only able to append image but before that i want to appendcaption, user_id, mobile_tauky_id.
NSString *urlString = #"http://182.73.152.59:82/php/tauky_services/codeigniter-restserver-master/index.php/api/uploadClass/uploadTauky/";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSLog(#"%#", request);
NSMutableData *body = [NSMutableData data];
//Image
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"image\"; filename=\"%#\"\r\n",imageData] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"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];
NSLog(#"Response : %#",returnString);
if([returnString isEqualToString:#"Success ! The file has been uploaded"]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Success" message:#"Image Saved Successfully" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
NSLog(#"Finish");
you can append one by one parameters such like as:-
NSURL *dataURL=[[NSURL alloc]initWithString:[NSString stringWithFormat:#"http://182.73.152.59:82/php/tauky_services/codeigniter-restserver-master/index.php/api/uploadClass/uploadTauky/"]];
NSMutableURLRequest *dataRqst = [NSMutableURLRequest requestWithURL:dataURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[dataRqst setHTTPMethod:#"POST"];
NSString *stringBoundary = #"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
NSString *headerBoundary = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",stringBoundary];
[dataRqst addValue:headerBoundary forHTTPHeaderField:#"Content-Type"];
NSMutableData *postBody = [NSMutableData data];
// -------------------- ---- caption ---------------------------\\
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Disposition: form-data; name=\"captionType\"\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[caption dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// -------------------- ---- user_id ---------------------------\
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Disposition: form-data; name=\"UserIdType\"\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[userId dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// -------------------- ---- mobile_tauky_id ---------------------------\
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Disposition: form-data; name=\"mobile_tauky_idType\"\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[mobile_tauky_id dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// -------------------- ---- blauky_id ---------------------------\
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Disposition: form-data; name=\"blauky_idType\"\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[blauky_id dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// media part
// -------------------- ---- Image Upload Status ---------------------------\
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Disposition: form-data; name=\"type\"\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];
NSString *mediaType=#"Image";
NSLog(#"type %#",mediaType);
[postBody appendData:[mediaType dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//pass MediaType file
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Disposition: form-data; name=\"Data\"; filename=\"image.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: image/png\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// get the image data from main bundle directly into NSData object
NSData *imgData = UIImagePNGRepresentation(Your Image);
// add it to body
[postBody appendData:imgData];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
// -------------------- ---- Audio Upload Status ---------------------------\
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Disposition: form-data; name=\"type\"\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];
NSString *mediaType=#"Audio";
NSLog(#"type %#",mediaType);
[postBody appendData:[mediaType dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//pass MediaType file
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Disposition: form-data; name=\"Data\"; filename=\"myVoice.mp3\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: audio/caf\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *url = [NSString stringWithFormat:#"%#/record.mp3", documentsDirectory];
// get the audio data from main bundle directly into NSData object
NSData *audioData;
audioData = [[NSData alloc] initWithContentsOfFile:url];
// add it to body
[postBody appendData:audioData];
[postBody appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
// final boundary
[postBody appendData:[[NSString stringWithFormat:#"--%#--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
// add body to post
[dataRqst setHTTPBody:postBody];
NSHTTPURLResponse* response =[[NSHTTPURLResponse alloc] init];
NSError* error = [[NSError alloc] init] ;
//synchronous filling of data from HTTP POST response
NSData *responseData = [NSURLConnection sendSynchronousRequest:dataRqst returningResponse:&response error:&error];
//convert data into string
NSString *responseString = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding];
NSLog(#"Response String %#",responseString);

how to share image to twitter from iphone application

I'm using twitter+OAuth with MGTwitterengine in my application and successfully post a comment to twitter. But now my problem is share image to twitter using
https://upload.twitter.com/1/statuses/update_with_media.json . I searched many web sites and get source code by using this direct upload to twitter api
https://upload.twitter.com/1/statuses/update_with_media.json . here the code is below.
-(void)UploadimageToTwitter
{
//NSString *boundary = #"----------------------------991990ee82f7";
// NSURL *finalURL = [NSURL URLWithString:#"http://upload.twitter.com/1.1/statuses/update_with_media.json"];
NSString *accessTokenKey = kOAuthaccessTokenKey;
NSString *secretTokenKey = kOAuthsecretTokenKey;
NSURL *finalURL = [NSURL URLWithString:#"http://upload.twitter.com/1/statuses/update_with_media.json"];
/*if (!finalURL)
{
return nil;
}*/
OAConsumer *consumer = [[OAConsumer alloc] initWithKey:kOAuthConsumerKey secret:kOAuthConsumerSecret];
//Shearing picture on twitter with Oauth without any third party api.
OAToken *token = [[OAToken alloc] initWithKey:accessTokenKey secret:secretTokenKey]; //Set user Oauth access token and secrate key
//OAConsumer *consumer = [[OAConsumer alloc] initWithKey:ConsumerToken secret:ConsumerSecrateKey]; // Application cosumer token and secrate key
OAMutableURLRequest *theRequest = [[OAMutableURLRequest alloc] initWithURL:finalURL consumer:consumer token:token realm: nil signatureProvider:nil];
[theRequest setHTTPMethod:#"POST"];
[theRequest setTimeoutInterval:120];
[theRequest setHTTPShouldHandleCookies:NO];
// Set headers for client information, for tracking purposes at Twitter.
[theRequest setValue:DEFAULT_CLIENT_NAME forHTTPHeaderField:#"X-Twitter-Client"];
[theRequest setValue:DEFAULT_CLIENT_VERSION forHTTPHeaderField:#"X-Twitter-Client-Version"];
[theRequest setValue:DEFAULT_CLIENT_URL forHTTPHeaderField:#"X-Twitter-Client-URL"];
NSString *boundary = #"--0246824681357ACXZabcxyz";// example taken and implemented.
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[theRequest setValue:contentType forHTTPHeaderField:#"content-type"];
// NSMutableData *body = [NSMutableData dataWithLength:0];
NSMutableData *body=[NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//status
[body appendData:[[NSString stringWithFormat:#"--%#\r\n\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"status\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"status\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithFormat:#"%#",status] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",#"Latest Uploading"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//media
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"media_data[]\"; filename=\"sunflower.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"media[]\"; filename=\"index.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type:application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
UIImage *image1=[UIImage imageNamed:#"sunflower.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image1, 1.0);
// [body appendData:[[NSString stringWithString:[UIImageJPEGRepresentation(image, 1.0) base64EncodingWithLineLength:0]] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[[NSString stringWithString:#"Honeymoon uploads image\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// --------------------------------------------------------------------------------
// modificaiton from the base clase
// our version "prepares" the oauth url request
// --------------------------------------------------------------------------------
[theRequest prepare];
NSString *oAuthHeader = [theRequest valueForHTTPHeaderField:#"Authorization"];
[theRequest setHTTPBody:body];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"oAuthHeader = %# =",oAuthHeader);
NSLog(#"ResponsString = \n%#",responseString);
}
Using this code i'm getting responsestring is below
{"errors":[{"message":"Internal error","code":131}]}
It is a server error or my error. really do not know where i was wrong in the above code.
if anybody know answer please guide to me. your help saved my life cause i was searching the above task past three months using three kind of different api's like Twitpic, yfrog and now post/update_with_media.
NSString *status = tweetText.text;
TWRequest *sendTweet;
if(image1 == nil)
{
sendTweet = [[TWRequest alloc]
initWithURL:[NSURL URLWithString:#"https://api.twitter.com/1/statuses/update.json"]
parameters:[NSDictionary dictionaryWithObjectsAndKeys:status, #"status", nil]
requestMethod:TWRequestMethodPOST];
}
else
{
sendTweet = [[TWRequest alloc] initWithURL:[NSURL URLWithString:#"https://upload.twitter.com/1/statuses/update_with_media.json"]
parameters:[NSDictionary dictionaryWithObjectsAndKeys:status, #"status",image1,#"media" , nil]
requestMethod:TWRequestMethodPOST];
[sendTweet addMultiPartData:[tweetText.text dataUsingEncoding:NSUTF8StringEncoding] withName:#"status" type:#"multipart/form-data"];
[sendTweet addMultiPartData:UIImagePNGRepresentation(image1) withName:#"media" type:#"multipart/png"];
}
sendTweet.account = self.account;
[sendTweet performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if ([urlResponse statusCode] == 200)
{
dispatch_sync(dispatch_get_main_queue(),
^{
[self displayText:#"Tweet Done"];
});
}
else
{
NSLog(#"Problem sending tweet: %#", error);
}
}];
Hope this code works for you, it works for me, in this you can post image as well as text only. Best of luck

Upload Image on tumblr in iPhone

I am really stuck with this issue for many days. In my app i need to upload image on tumblr, i have tried various tutorials and updates however none of them is working for posting images on tumblr.Please help me any one if you have done this.
NSData *imageData = [NSData dataWithContentsOfFile:photo];
//stop on error
if (!imageData) return NO;
//Create dictionary of post arguments
NSArray *keys = [NSArray arrayWithObjects:#"email",#"password",#"type",#"caption",nil];
NSArray *objects = [NSArray arrayWithObjects:
tumblrEmail,
tumblrPassword,
#"photo", caption, nil];
NSDictionary *keysDict = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
//create tumblr photo post
NSURLRequest *tumblrPost = [self createTumblrRequest:keysDict withData:imageData];
[keysDict release];
//send request, return YES if successful
NSURLConnection *tumblrConnection = [[NSURLConnection alloc] initWithRequest:tumblrPost delegate:self];
if (!tumblrConnection)
{
NSLog(#"Failed to submit request");
return NO;
}
else
{
NSLog(#"Request submitted");
receivedData = [[NSMutableData data] retain];
[tumblrConnection release];
return YES;
}
-(NSURLRequest *)createTumblrRequest:(NSDictionary *)postKeys withData:(NSData *)data
{
//create the URL POST Request to tumblr
NSURL *tumblrURL = [NSURL URLWithString:#"http://api.tumblr.com/v2/blog/kashifjilani.tumblr.com/posts"];
NSMutableURLRequest *tumblrPost = [NSMutableURLRequest requestWithURL:tumblrURL];
[tumblrPost setHTTPMethod:#"POST"];
//Add the header info
NSString *stringBoundary = #"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",stringBoundary];
[tumblrPost addValue:contentType forHTTPHeaderField: #"Content-Type"];
//create the body
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
//add key values from the NSDictionary object
NSEnumerator *keys = [postKeys keyEnumerator];
int i;
for (i = 0; i < [postKeys count]; i++) {
NSString *tempKey = [keys nextObject];
[postBody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",tempKey] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"%#",[postKeys objectForKey:tempKey]] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
//add data field and file data
[postBody appendData:[#"Content-Disposition: form-data; name=\"data\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:data]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
//add the body to the post
[tumblrPost setHTTPBody:postBody];
return tumblrPost;
}
This works for me:
NSData *imageData = UIImageJPEGRepresentation(yourUploadImage, 0.9);
NSMutableURLRequest *aRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[aRequest setURL:[NSURL URLWithString:#"https://www.tumblr.com/api/write"]];
[aRequest setHTTPMethod:#"POST"];
NSString *boundary = #"0xKhTmLbOuNdArY";
//NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[aRequest addValue:contentType forHTTPHeaderField: #"Content-Type"];
/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"email\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:Tumblr_UserName_Here dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"password\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:Tumblr_Password_Here dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"type\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"photo" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"data\"; filename=\"upload.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Transfer-Encoding: image/jpg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
if(comment available here)
{
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"caption\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[commentString dataUsingEncoding:NSUTF8StringEncoding]];
}
// setting the body of the post to the reqeust
[aRequest setHTTPBody:body];
[NSURLConnection connectionWithRequest:aRequest delegate:self];
Now delegate of NSURLConnection
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(connection)
NSLog(#"Success");
else
NSLog(#"Something Wrong");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
{
NSLog(#"%#",[error description]);
}
I've been struggling with this for a long time too, but I figured out how to post easily.
You can see my post for an answer to this. If you have any problem with it, I'd be glad to help.

How to change sendSynchronousRequest to sendASynchronousRequest in ios?

I am uploading image on server.
how to change Synchronous request to ASynchronous request. because i wanna use progressbar while uploading image..
My code is.
+(NSDictionary *)UploadPhoto :(UIImage *)image{
NSString *DeviceId;
NSString *TokenValue=tokenTemp;
DeviceId = DevID;
NSString *Nonce=[self generateRandomString];
NSString *currentTimeStamp = [self GetTimeStamp];
NSString *Cipher=[NSString stringWithFormat:#"%#%#%#%#%#",mySecret,DeviceId,Nonce,currentTimeStamp,TokenValue];
Cipher=[Cipher URLDecodedString];
Cipher=[self GetCipher:Cipher];
UIImage *TempPicture=image;//[UIImage imageNamed:imageName];
NSData *PictureData=UIImageJPEGRepresentation(TempPicture, 1.0);
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#Messages.php",WebServiceUrl]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setTimeoutInterval:20.0f];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"multipart/form-data; boundary=*****" forHTTPHeaderField:#"Content-Type"];
NSMutableData *postBody = [NSMutableData data];
NSString *stringBoundary = [NSString stringWithString:#"*****"];
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"method\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"%#",#"Upload"] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"Type\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"%#",#"0"] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"Name\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"%#",#"XYZ ****************"] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"--%#\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"MessageImage\"; filename=\"c.png\"\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[NSData dataWithData:PictureData]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSASCIIStringEncoding]];
[request setHTTPBody: postBody];
[request setValue:Cipher forHTTPHeaderField:#"Cipher"];
[request setValue:DeviceId forHTTPHeaderField:#"Deviceid"];
[request setValue:Nonce forHTTPHeaderField:#"Nonce"];
[request setValue:currentTimeStamp forHTTPHeaderField:#"Timestamp"];
[request setValue:TokenValue forHTTPHeaderField:#"Token"];
[request setHTTPBody:postBody];
NSError *error;
NSHTTPURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
if (!data) {
NSLog(#"nil");
}
NSDictionary *temp= [response allHeaderFields];
NSString *temp2= [temp objectForKey:#"Responsecode"];
if(temp2!=nil && [temp2 length]>0)
{
}
else
{
}
return temp;
}
Thanks..
please help..
how to call
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite in this code..
If you want to want to track the upload progress, you have to use
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]
and implement all the NSURLConnectionDelegate methods. This is described in this Apple documentation.
In particular the connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite: delegate methods informs you about the upload progress.
Another advantage of this method is that you can cancel a request, which is not possible with sendSynchronousRequest or sendASynchronousRequest.

NSData and Uploading Images via POST in iOS

I have been combing through the many many posts about uploading images via POST in iOS. Despite the wealth of information on this topic, I cannot manage to correctly upload JPEG data taken from my iPhone Simulator Photo Library.
The data, once on the server, is just a huge string of hexidecimal. Shouldn't NSData just be a byte stream? I don't get whats going on with all the hex, or why this code seems to work for everyone else.
Here is the code in question:
-(void)uploadWithUserLocationString:(NSString*)userLocation{
NSString *urlString = #"http://some.url.com/post";
// set up the form keys and values (revise using 1 NSDictionary at some point - neater than 2 arrays)
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth",#"text",#"location",nil];
NSArray *vals = [[NSArray alloc] initWithObjects:self.authToken,self.textBox.text,userLocation,nil];
// set up the request object
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
//Add content-type to Header. Need to use a string boundary for data uploading.
NSString *boundary = [NSString stringWithString:#"0xKhTmLbOuNdArY"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//create the post body
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
//add (key,value) pairs (no idea why all the \r's and \n's are necessary ... but everyone seems to have them)
for (int i=0; i<[keys count]; i++) {
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n",[keys objectAtIndex:i]] dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",[vals objectAtIndex:i]] dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
}
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"image\"\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSASCIIStringEncoding]];
[body appendData:[NSData dataWithData:self.imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSASCIIStringEncoding]];
// set the body of the post to the reqeust
[request setHTTPBody:body];
// make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(returnString);
[keys release];
[vals release];
}
Thanks for your time.
This code works in my app. If you're not using ARC you'll need to modify the code to release anything alloc'ed.
// 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=%#", boundary];
[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", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set URL
[request setURL:requestURL];
i hope this code will help some body else ...
//create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//Set Params
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
//Create boundary, it can be anything
NSString *boundary = #"------VohpleBoundary4QuqLuM1cE5lMwCy";
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
//Populate a dictionary with all the regular values you would like to send.
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:param1 forKey:#"param1-name"];
[parameters setValue:param2 forKey:#"param2-name"];
[parameters setValue:param3 forKey:#"param3-name"];
// add params (all params are strings)
for (NSString *param in parameters) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
NSString *FileParamConstant = #"imageParamName";
NSData *imageData = UIImageJPEGRepresentation(imageObject, 1);
//Assuming data is not nil we add this to the multipart form
if (imageData)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] 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]];
}
//Close off the request with the boundary
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the request
[request setHTTPBody:body];
// set URL
[request setURL:[NSURL URLWithString:baseUrl]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if ([httpResponse statusCode] == 200) {
NSLog(#"success");
}
}];
Take a look at Apple's SimpleURLConnections example project. You can use the PostController from there with a few modifications.
However - it's not exactly simple. The difference to the solution above is that Apple's is using a stream to stream the file to the server. That's much more memory-friendly than keeping the encoded image data around for the duration of the upload. It's also way more complicated.
NSData *imgData = UIImagePNGRepresentation(imgUser.image);
NSString *str=[NSString stringWithFormat:#"%#upload_image",appDelegate.strRoot];
NSString *urlString = [NSString stringWithFormat:#"%#",str];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"file\"; filename=\"a.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imgData]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// parameter UserId
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userid\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[appDelegate.strUserID dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the request
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
NSLog(#"%#",dict);
I see that you send multiple files in one request, correct?
From HTTP specification, you should use multipart/mixed Content-type inside embedding multipart/form-data
Example from link above:
Content-type: multipart/form-data, boundary=AaB03x
--AaB03x
content-disposition: form-data; name="field1"
Joe Blow
--AaB03x
content-disposition: form-data; name="pics"
Content-type: multipart/mixed, boundary=BbC04y
--BbC04y
Content-disposition: attachment; filename="file1.txt"