I am working with web services using json parsing. I am able to get images from the web services, can someone help me how to post an image? How i can post an image to the web services?
it will be something along the lines of this...
NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:#"you url"];
[mutableRequest addValue:#"image/jpeg" forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:UIImageJPEGRepresentation(self.image, 0.9)]];
[mutableRequest setHTTPBody:body];
NSURLResponse *response;
NSError *error;
(void) [NSURLConnection sendSynchronousRequest:mutableRequest returningResponse:&response error:&error];
Thanks
Find here serverside (PHP) coding for image Upload with random name. also it will give the image link as response.
//Create a folder named images in your server where you want to upload the image.
// And Create a PHP file and use below code .
<?php
$uploaddir = 'images/';
$ran = rand () ;
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir .$ran.$file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "www.host.com/.../images/{$uploadfile}";
}
?>
And Here is iOS code
- (IBAction)uploadClicked:(id)sender
{
/*
turning the image into a NSData object
getting the image back out of the UIImageView
setting the quality to 90
*/
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 90);
// setting up the URL to post to
NSString *urlString = #"your URL link";
// 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:#"rn--%#rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name="userfile"; filename="ipodfile.jpg"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-streamrnrn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"rn--%#--rn",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);
}
Check below good tutorial.In that tutorial you able to find the ios side code as well server side php code too.
http://zcentric.com/2008/08/29/post-a-uiimage-to-the-web/
The best way to use ASIHttpFormData Click here to know how to use
Related
I am uploading images to hosting server via browser (simple html form) the images can be uploaded without any problem but when I try to upload via iPhone it does not post the image to server.
Here is my code:
NSString *urlString = #"http://example.com/fileupload.php";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; 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:[[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] autorelease];
NSLog(#"Response: %#",returnString);
I am using the same code on a different hosting server and working fine there.
I have checked the folder has 777 permissions.
Thanks.
Remove below lines, and it should work
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
First select an image
Code ::
#property(nonatomic, retain) UIImage *capturedImg;
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
NSData *dataImage = UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"], 1);
capturedImg = [UIImage imageWithData:dataImage];
}
For Uploading image,
Code ::
NSData *imgData = UIImageJPEGRepresentation(capturedImg, 0.8);
And, this imgData will be used for uploading image as data
Change ::
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"a.jpg\"\r\n"]] dataUsingEncoding:NSUTF8StringEncoding]]; // 'userfile' to 'file'
Hopefully, it will help to you.
Thanks.
Thank you very much all for your help but the problem was on the server side. I don't know why the server sometimes rejects the file and sometimes it works fine.
Thanks again.
is it possible to upload an entire plist file to a remote server or to dropbox programmatically from an iPhone?
Any useful info will be helpful. If you have codes pls share thanks! :)
EDIT:
I'm currently using these codes i got it from Upload File to FTP Server on iPhone. But i'm having errors, my plist is in the document dir.
Function
- (BOOL) uploadData:(NSData *)plistData filename:(NSString *)filename {
NSString *urlString = #"http://site.net/upload.php";
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"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#\"\r\n",filename]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:plistData]];
[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(#"Uploaded: %#", returnString);
return ([returnString isEqualToString:#"OK"]);
}
Call method
[self uploadData:[NSKeyedArchiver archivedDataWithRootObject:dbArray] filename:#"data.plist"];
PHP file
<?php
$uploaddir = '';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "OK";
} else {
echo "ERROR";
}
?>
It just keeps throwing "ERROR"...
For a generic server you just need to write script (e. g. using PHP) that will accept POST requests. You can then upload your file using NSURLConnection.
As usual, the official documentation has you covered. As for the server side script, that depends on what language/toolkit you choose. PHP’s move_uploaded_file() is just one of the possibilities.
- (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
I need to POST a request. The request has 3 parameters, 'email_id' , 'location' and 'image_data'. The value for 'image_data' contains NSData jpeg representation of a UIImage. The request must be submitted using a content type of multipart/form-data. How can I create the NSMutableRequest for posting this request? How should I set the boundary? Is the boundary required for the entire packet or is it enough only for the image part?
This link:
http://iphone.zcentric.com/2008/08/29/post-a-uiimage-to-the-web/
Should contain all you need. U'll need to extend the PHP-script to handle your non-image parameters but this is what I used. :)
Edit: Noticed the previous link was broken. The new one works
If I were you, I'd check out the ASIHTTPRequest library. It's an HTTP client library for Cocoa that makes life EVER so much easier for people who do a lot of web interactions from their iPhone apps.
Here's me, using ASIFormDataRequest (a component of ASIHTTPRequest) to upload an image from my iPhone app. The client's term for these images is "marks"--they're going on a map of local pictures taken by users all around the local area. Users are invited to "make your mark". You can imagine the hilarity that ensues.
Anyhoo, self.mark is an instance of my Mark class that encapsulates the data about an image-and-details package I'm uploading. I have a data manager singleton I use in the first line of this method, which contains the current CLLocation, so I can get geocode info for this picture.
Notice I don't concern myself with encoding types or multipart boundaries. The library handles all that.
-(void)completeUpload
{
CLLocation *currentLoc = [DataManager sharedDataManager].currentLocation;
self.mark.latitude = [NSNumber numberWithDouble:currentLoc.coordinate.latitude];
self.mark.longitude = [NSNumber numberWithDouble:currentLoc.coordinate.longitude];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:
[NSURL URLWithString:[NSString stringWithFormat:#"%#image_upload.php", WEBAPPURL]]];
[request setPostValue:self.mark.titleText forKey:#"title"];
[request setPostValue:self.mark.descriptionText forKey:#"description"];
[request setPostValue:self.mark.event.guid forKey:#"event"];
[request setPostValue:self.mark.latitude forKey:#"latitude"];
[request setPostValue:self.mark.longitude forKey:#"longitude"];
[request setPostValue:self.mark.project forKey:#"project"];
[request setPostValue:[[NSUserDefaults standardUserDefaults] valueForKey:#"userID"] forKey:#"user_id"];
request.timeOutSeconds = 120;
int i = 1;
for (NSString *tag in self.tags) {
[request setPostValue:tag forKey:[NSString stringWithFormat:#"tag-%d", i]];
i++;
}
NSData *imageData = UIImagePNGRepresentation(self.mark.image);
NSData *thumbData = UIImagePNGRepresentation(self.mark.thumbnail);
[request setData:imageData forKey:#"file"];
[request setData:thumbData forKey:#"thumb"];
self.progress.progress = 20.0;
[request setUploadProgressDelegate:self.progress];
request.showAccurateProgress = YES;
request.delegate = self;
[request startAsynchronous];
}
EDIT: By the way, the PHP script I'm posting to is behind HTTP authentication. ASI caches those credentials, and I provided them earlier, so I don't have to provide them again here. I note that because otherwise, the way this post and the corresponding PHP script is written, anybody could fake anybody else's user ID value and post whatever under their username. You have to think about web-application security when you build an app like this, no different than if it was a web site. It IS a web site, actually, just browsed through a non-traditional client.
NSData *imageData=UIImageJPEGRepresentation(imageview.image, 1.0);
NSString *filename=#"nike.jpg"
NSString *urlString = #"http://xyz.com/file_upload/file1.php";
NSMutableURLRequest *request =[[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"-----------------99882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSMutableString * string = [[NSMutableString alloc] init];
[string appendFormat:#"\r\n\r\n--%#\r\n", boundary];
[string appendFormat:#"Content-Disposition: form-data; name=\"emailid\"\r\n\r\n"];
[string appendFormat:#"pradz39#gmail.com"]; //value
[body appendData:[string dataUsingEncoding:NSUTF8StringEncoding]]; // encrypt the entire body
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#\"\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]];
[string release];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
I would like to implement logic that uploads file to FTP Server.
I am new in iPhone development, so want to figure out preferred approach. After browsing available API for this task I have managed to find only code that uses CFNetwork (that looks like not Objective C based).
There is also URL Loading System that uses NSURL etc which are Objective C based.
So, my question: Is it possible to use URL Loading System to implement file upload to FTP Server?
Thanks.
I use a PHP Page to post a file to and have PHP handle the uploading....
This code is used to upload a photo, but it can be adapted to work with any file.
PHP Code:
<?php
$uploaddir = 'photos/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "OK";
} else {
echo "ERROR";
}
?>
iPhone Code:
- (BOOL)uploadImage:(NSData *)imageData filename:(NSString *)filename{
NSString *urlString = #"http://www.yourdomainName.com/yourPHPPage.php";
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"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#\"\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] autorelease];
return ([returnString isEqualToString:#"OK"]);
}
Method Call:
[self uploadImage:UIImageJPEGRepresentation(imageView.image, 1.0) filename:imageName];