Blank image with POST - iphone

I've an issue with the post of an UIImage on a PHP server, when I post it, the image received is empty.
The method I use is :
- (void)uploadImage {
/*
turning the image into a NSData object
getting the image back out of the UIImageView
setting the quality to 90
*/
NSData *imageData = UIImageJPEGRepresentation(myImage, 0.9);
// setting up the URL to post to
NSString *urlString = #"http://myserver/test.php";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type
You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request 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:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] 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]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets 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);
}
Taken from : http://iphone.zcentric.com/2008/08/29/post-a-uiimage-to-the-web/
Thanks for your help !

I suggest the use of ASIHTTPRequest for this kind of requests. You can do this much more easily with it. Here is an example to how send an image using ASIHTTPRequest:
// Initilize Queue
networkQueue = [[ASINetworkQueue alloc] init];
[networkQueue setUploadProgressDelegate:statusProgressView];
[networkQueue setRequestDidFinishSelector:#selector(imageRequestDidFinish:)];
[networkQueue setQueueDidFinishSelector:#selector(imageQueueDidFinish:)];
[networkQueue setRequestDidFailSelector:#selector(requestDidFail:)];
[networkQueue setShowAccurateProgress:true];
[networkQueue setDelegate:self];
NSData *imageData = UIImageJPEGRepresentation(yourImage, compression);
url = [NSURL URLWithString:#"http://myserver/upload.php"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:#"myImageName" forKey:#"name"];
[request addData:imageData withFileName:#"someFileName.jpeg" andContentType:#"image/jpeg" forKey:#"uploadedImage"];
[networkQueue addOperation:request];
[networkQueue go];
Hope it helps

Related

How to upload image to a url using post request asynchronously?

I have to upload an image to a specific url. The specifications that I have to follow are these:
1. Method should be post
2. Image must be uploaded using multipart HTTP content type
3. The name of the HTTP field should be “uploadingTheFile”.
4. Multipart data shiuld have filename.
5. Image content type should be among following-jpeg,jpg,png,gif
I want to upload using NSURLConnection asynchronously. I think I am not able to set the parameters in the request in a proper way.I am getting status code as 200 which suggests that there is no problem with my NSURLConnection delegate methods. The code that I am trying is :
NSString *stringBoundary=#"0xKhTmLbOuNdArY";
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#",stringBoundary] forHTTPHeaderField:#"uploadfile"];
NSMutableData *postBody = [NSMutableData data];
NSData *imageData=UIImagePNGRepresentation([UIImage imageNamed:#"IMG_0215.JPG"]);
//[postBody appendData:imageData];
[postBody appendData:[#"Content-Disposition: form-data; name=\"data;filename=\"media.png\"\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:imageData]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
self.data = [NSMutableData data];
}
I am using following code and it is working fine for me.
NSData *imageData = UIImageJPEGRepresentation(empImgView.image, 90); // convert image in NSData
NSString *urlString = #"http://abc.com/saveimage/Default.aspx"; // your url
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]];
NSString *imgNameString = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.jpg\"\r\n",[responseSrting substringWithRange:NSMakeRange(1, responseSrting.length - 2)]];
[body appendData:[[NSString stringWithString:imgNameString] 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(#"%#",returnString);
Here you can learn how to use afnetworking for upload images
https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
You can use AFNetworking (it is opensource), here is code that worked for me. This is for AFNetworking 3.0 version.
NSString *serverUrl = [NSString stringWithFormat:#"http://www.yoursite.com/uploadlink", profile.host];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:serverUrl parameters:nil error:nil];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURL *filePath = [NSURL fileURLWithPath:[url path]];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath 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
LLog(#"progres increase... %# , fraction: %f", uploadProgress.debugDescription, uploadProgress.fractionCompleted);
});
} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];

Error sending http post request with image

I'm stucked in this problem since days and i really need your help.
I'm actually trying to upload a file from my iphone app to a webserver trough a php script.
this is my method in Xcode:
-(void)sendPost{
UIImageView *imageView = [[UIImageView alloc] init];
imageView.image = [UIImage imageNamed:#"back.png"];
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 90);
NSString *urlString = #"myscriptishere.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setTimeoutInterval:60.0];
[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=\"userfile\";filename=\"myfile.png\"\r\n"]
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];
NSLog(#"%#",[[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] encoding:NSUTF8StringEncoding]);
// Do any additional setup after loading the view.
}
and my php code is:
<?php
$domainpath = $_SERVER['DOCUMENT_ROOT'];
$target = "./upload";
$public = "/public/upload/";
$target = $target.basename( $_FILES['userfile']['name']) ;
$check = getimagesize($_FILES['userfile']['tmp_name']);
if (move_uploaded_file($_FILES["file"]["tmp_name"],
$domainpath. $public . $_FILES["file"]["name"]))
echo "YES";
else
echo "NO";
?>
I always receive (after few seconds, so I guess I'm uploading something) the server reply "NO".
I already checked I have permission on the folder I'm going to write in.
Any ideas on where the problem could be hidin?
Thanx in advance
Your problem is here:
NSString *urlString = #"myscriptishere.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setTimeoutInterval:60.0];
[request setURL:[NSURL URLWithString:urlString]];
You are posting to a filename. Your urlString variable should hold full address including protocol and domain (like #"http://localhost/myscriptishere.php").

Object reference not set to an instance of an object In XML

I am new to iPhone and using XML in my application where i need to send one image to the server's one specific folder. For the same i am using the code :
NSString *filename = #"Image";
NSData *imageData = UIImageJPEGRepresentation([imageView image], 90);
NSString *urlString = [NSString stringWithFormat:#"http://111.111.11.1/webservices.asmx/PutImage"];
//url is : http://111.111.11.1/webservices.asmx/PutImage?ImgIn=image.jpg
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"--------1473780983"];
NSString *contentType = [NSString stringWithFormat:#"application/x-www-form-urlencoded;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 stringWithFormat:#"Content-Disposition: form-data; name=\"images\"; filename=\"%#.jpg\"\r\n", filename] 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(#"\n\n\nreturnString : %#",returnString);
I am getting message like : "Object reference not set to an instance of an object" in return string. Can anybody guide me with some solution?
Ok... Try my code that i m using....
//imageview is a UIImageView
NSData *imageData = UIImageJPEGRepresentation(imageview.image, 100);
// setting up the URL to post to
NSString *urlString = #"http://example.com/upload";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type
You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request 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:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n"] 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]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
self.returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
To upload data from your iPhone to your server:
- (void)sendImage {
NSData *postData = [nsdata from your original image];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Init and set fields of the URLRequest
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:[NSString stringWithString:#"http://yoururl.domain"]]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
// Return data of the request
NSData *receivedData = [[NSMutableData data] retain];
}
[request release];
}

way to start activity indicator on click event of button before its touch ends?

i working on uploading the images through my application.i used the following code
-(IBAction)submitimage:(id)sender
{
// [activity startAnimating]; i started activity here but it starts after completion of function
NSString *name, *comments;
comments = txtcomment.text;
name = #"Anonymous";
int r=random()%10000;
NSLog(#"random number:%d",r );
NSString *imageName=[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"dashboard\"; filename=\"%d.jpg\"\r\n",r];
NSData *imageData = UIImageJPEGRepresentation(imge, 90);
//NSLog(#"imagedata=%#",imageData);
NSString *urlString =[NSString stringWithFormat:#"http://www.xyzsite.com/webservices/&comment=%#&name=%#",comments,name];
//NSLog(#"urlsubmit=%#",urlString);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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"];
/* body of the post */
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:imageName] 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(#"%#",returnString);
}
but the animation starts after function over so is there any other way to start activity indicator.before the touch event over.i face the same problem in two different application of uploading images.so if anyone knows then plese let me know
thanks
There could be more than one solution to this. However you can move the activity indication start animation action to the TouchDown event and leave the other in Touch up Inside.

what changes are needed in this code of upload image and get responce from server

- (IBAction) uploadImage {
/*
turning the image into a NSData object
getting the image back out of the UIImageView
setting the quality to 100
*/
NSData *imageData = UIImageJPEGRepresentation(image.image, 100);
// setting up the URL to post to
NSString *urlString = #"http://uploadhere.com/photos/iphone.php";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type
You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request 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:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"q\"\r\n\r\n"] 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]];
NSLog(#"here1");
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSLog(#"here2");
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"here3");
//NSLog(returnString);
//picText = rowZero.pickerLabel.text;
NSLog(#"here4");
rowZero.path = returnString;
//NSLog(rowZero.path);
}
I have taken this code from some example and I am using it in my application...but I don't know why it is showing me that image is not actually being uploaded...can anyone please tell me whats going wrong??
please change this
NSData *imageData = UIImageJPEGRepresentation(image.image, 100);
NSData *imageData = UIImageJPEGRepresentation(urimageRepresentation, 100);
to ur own image representaion