objective-c - Doesn't upload file's content - iphone

I want to upload a local word (or rtf) file to my server. Uploads the file without content. There is no error code or anything..
NSString *urlString = #"http://myserver.com/upload-c.php";
NSString *filename=#"xx.docx";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"xx.docx"]];
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:data]];
[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(#"%#",returnString);

One obvious problem is with how you initialize your data variable.
Assuming "xx.docx" is the file you wish to upload, you have two problems.
You need to specify the full path to the file, not just the filename.
Since you are creating an NSURL from a file path, you need to use fileURLWithPath:, not URLWithString:.
Edit: Based on your comments, the file is located in the app's resource bundle. To get its fullpath you should do this:
NSString *fullPath = [[NSBundle mainBundle] pathForResource:#"xx" ofType:#"docx"];
NSData *data = [NSData dataWithContentsOfFile:fullPath];
Also, this line:
[body appendData:[NSData dataWithData:data]];
should simply be:
[body appendData:data];
And get rid of the calls to stringWithString:. Example:
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
should be:
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
and:
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
should be:
NSString *boundary = #"---------------------------14737809831466499882746641449";

Related

Upload pdf data to server

I want to send my pdf file data do server with some user data also like userId and fileName.
I have tried 2 solutions but not got the pdf file on backend. Even i am having the pdf file in my document directory and it is opening successfully.
Tried 1:
-(void)uploadDock{
NSString *fileName =[NSString stringWithFormat: #"%#.pdf",#"Inspection"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *data=[NSData dataWithContentsOfFile:path];
NSString *content=[data base64EncodedString];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if ([self.responseData retainCount]) {
NSLog(#"Do nothing");
[self.responseData release];
}
self.responseData=[[NSMutableData alloc]init];
NSURL *url = [NSURL URLWithString:#"http://abcgroup.delivery-projects.com:81/api/index.php?keyword=docinsert"];
//self.request = [NSMutableURLRequest requestWithURL:url
//cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
self.request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"Requst %#",request);
NSString *userid=[userDefaults valueForKey:#"UIDD"];
NSString *title=fileName;
NSString *docname=fileName;
NSString *size=[NSString stringWithFormat:#"%d",[data length]];
NSString *post = [NSString stringWithFormat:#"userid=%#&title=%#&docname=%#&size=%#&content=%#",userid,title,docname,size,content];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
[self.request setHTTPMethod:#"POST"];
//NSString *POSTBoundary = [NSString stringWithFormat:#"0xKhTmLbOuNdArY"];
//[self.request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#\r\n", POSTBoundary] forHTTPHeaderField:#"Content-Type"];
[self.request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[self.request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[self.request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:self.request delegate:self];
}
Tried 2:
I am reading the NSData of pdf file from Document directory.
/////
-(void)uploadDock{
self.condition=3;
NSString *fileName =[NSString stringWithFormat: #"%#.pdf",#"Inspection"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *data=[NSData dataWithContentsOfFile:path];
NSString *content=[data base64EncodedString];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if ([self.responseData retainCount]) {
NSLog(#"Do nothing");
}
else{
self.responseData=[[NSMutableData alloc]init];
}
NSURL *url = [NSURL URLWithString:#"http://abcgroup.delivery-projects.com:81/api/index.php?keyword=docinsert"];
//self.request = [NSMutableURLRequest requestWithURL:url
// cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
self.request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"Requst %#",request);
NSString *userid=[userDefaults valueForKey:#"UIDD"];
NSString *title=fileName;
NSString *docname=fileName;
NSString *size=[NSString stringWithFormat:#"%d",[data length]];
/*
NSString *post = [NSString stringWithFormat:#"userid=%#&title=%#&docname=%#&size=%#&content=%#",userid,title,docname,size,content];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
[self.request setHTTPMethod:#"POST"];
//NSString *POSTBoundary = [NSString stringWithFormat:#"0xKhTmLbOuNdArY"];
//[self.request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#\r\n", POSTBoundary] forHTTPHeaderField:#"Content-Type"];
[self.request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[self.request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[self.request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:self.request delegate:self];
*/
/////
NSMutableURLRequest *request11 = [[NSMutableURLRequest alloc] init] ;
[request11 setURL:url];
[request11 setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request11 addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
// Pdf File
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"content\"; filename=\"INSPECTION.pdf\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[#"Content-Disposition: form-data; name=\"content\"\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[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:[[NSString stringWithFormat:#"%#",userid] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"title\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",#"TITLE_TEST1"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"docname\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",docname] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"size\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",size] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[request11 setHTTPBody:body];
[NSURLConnection connectionWithRequest:request11 delegate:self];
//[NSURLConnection sendSynchronousRequest:request11 returningResponse:nil error:nil];
/////
}
I used following function to upload images, audio and videos with slight modifications.
In this function urloptions is the query string that you want to send with file like userId and fileName.
Didn't get chance to upload PDF but hope this will help you.
-(NSString *)uploadFile:(NSString *)urloptions: (NSString *) ext :(NSData *)imageData{
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#&%#",APP_URL,urloptions]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[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 stringWithFormat:#"Content-Disposition: form-data; name=\"formFile\"; filename=\".%#\"\r\n",ext] 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];
//NSLog(#"%#",returnString);
return returnString ;
//[returnString release];
}
While you can find a way to correctly post your data, it will be much easier and maintainable to use a wrapper around NSURLConnection such as STHTTPRequest https://github.com/nst/STHTTPRequest. Here is what your code will look like:
STHTTPRequest *r = [STHTTPRequest requestWithURLString:#"http://abcgroup.delivery-projects.com:81/api/index.php?keyword=docinsert"];
[r setFileToUpload:#"Inspection.pdf" parameterName:#"myFile"];
[r setPOSTDictionary:#{#"userid":#"", #"title":#"", #"docName":#""}]; // your parameters here
r.completionBlock = ^(NSDictionary *headers, NSString *body) {
// ...
};
r.errorBlock = ^(NSError *error) {
// ...
};
[r startAsynchronous];
To upload any type of file you can use ASIHttpRequest library that you can get from https://github.com/pokeb/asi-http-request.
To upload file use ASIFormDataRequest class of this library that makes your work easy.
first convert your pdf in binary
NSData theData = [NSData dataWithData:[GTMBase64 decodeString:theBinary]]; //first transfer it to NSData.
[m_oTestingWeb loadData:theData
MIMEType:#"application/pdf"
textEncodingName:#"UTF-8"
baseURL:nil]; //using the web view to show it back
then upload this data to server.
You have to create an API on the web server that the iPhone can contact in order to POST data to your web server. You can simply create an NSURLConnection in order to build your packet to post the data from the iPhone app.
Inside an NSURLConnection you can tell it to be a POST packet and then add data to the body of the request. Your image data should be converted to UTF8 and stored as a nvarchar or something along those lines in your database.
Understand, this is an overview of what you have to do, without knowledge of your internal workings of the web app I cannot give you specifics.
You can use the latest Library by AFNewtork:
With AFNetworking you can do it by:
NSURL *url = [NSURL URLWithString:#"my_base_url"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"yourfile.pdf"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:#"MainMedia" fileName:#"MainMedia" mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation start];
}
Download AFNetworking library and add it to your project.
Two real issues that I can spot in "Tried 2"
It seems, you forgot the final delimiter - see Irfan DANISH post.
You need the binary of the pdf - not the UTF8.
Additionally, do not use a synchronous request - use the asynchronous style implementing the delegate methods.
And, you "should" set a Content-Length header for the pdf part.

Upload zip file with Parameters [duplicate]

This question already has an answer here:
How can i upload file and other parameter using NSURLConnection
(1 answer)
Closed 9 years ago.
I am trying to upload a file using NSURLConnection using POST method. and also I need to send few parameters in Post like username etc.
I am trying this since morning Please help me guys.
NSString *urlString = #"http://test.com/upload.aspx";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"0xLhTaLbOkNdArZ"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//Reading the file
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"test.zip"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"test.zip\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:myData];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSError *returnError = nil;
NSHTTPURLResponse *returnResponse = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&returnResponse error:&returnError];
Try this

How to upload image to server from gallery as JSON on iOS

How can I upload an image to a server from the gallery on iPhone as JSON? I tried the following:
[Loading startLoading:YES];
NSString *urlString = [NSString stringWithFormat:#"http://railsboxtech.com/singing/jsn_song/register_response.php?accesstoken=%#",Access_Token];
//username, password, name, email, country
NSString *parameter = [NSString stringWithFormat:#"username=%#&password=%#&fname=%#&email=%#&lname=%#&btnImage4=%#",userField.text,passField.text,fnameField.text,emailField.text,lnameField.text,btnImage4];
NSConnection *conn = [[NSConnection alloc] initWithDelegate:self];
[conn sendRequest:urlString withParaMeter:parameter withMethod:#"POST" withTag:1];
[conn startAsynchronousRequest];
if you want to upload an image as a string you must convert your image data to Base64, then you can use your above method:-
For converting to a base64 string, refer to this Stack Overflow answer. You can then use your code for uploading.
Another Way
You can directly upload an image like so:
-(void)uploadImage
{
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *urlString = [ NSString stringWithFormat:#"http://yourUploadImageURl.php?intid=%#",1];
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", 1]] 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];
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

File upload server from iphone app [duplicate]

I want upload image to sever in iphone app I am using following code for PHP
but using this code i get error displayed on page when i run localhost/upload.php;
<?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";
}
?>
Below is the iphone xcode code
- (BOOL)uploadImage:(NSData *)imageData filename:(NSString *)filename{
NSString *urlString = #"http://localhost/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: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"]);
}
Calling method
[self uploadImage:UIImageJPEGRepresentation(imageView.image, 1.0) filename:#"pig.jpg"];
if you think error in php code then first try this print_r($_FILES); and see what did you get in the $_FILES['userfile']
try this and also did you check in php by print_r($_FILES);
NSString *urlString = #"http://localhost/upload.php";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
[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 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: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];

Uploading image to server in iphone application

I want upload image to sever in iphone app I am using following code for PHP
but using this code i get error displayed on page when i run localhost/upload.php;
<?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";
}
?>
Below is the iphone xcode code
- (BOOL)uploadImage:(NSData *)imageData filename:(NSString *)filename{
NSString *urlString = #"http://localhost/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: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"]);
}
Calling method
[self uploadImage:UIImageJPEGRepresentation(imageView.image, 1.0) filename:#"pig.jpg"];
if you think error in php code then first try this print_r($_FILES); and see what did you get in the $_FILES['userfile']
try this and also did you check in php by print_r($_FILES);
NSString *urlString = #"http://localhost/upload.php";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
[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 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: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];