Upload pdf data to server - iphone

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.

Related

How to post text and image data in NSMutableUrlRequest?

I m supposed to post the session ID, that is generated during validation of credentials and image data. But the image and session ID is not uploaded.
It was working fine when I used ASIHTTPRequest, later when i tried with NSMutableUrlRequest and NSURLConnection it doesnot seem to work.
Given below is the code used to POST image and Session ID
- (void)postinDataToServer:(NSData *)inData
{
//inData is the image data.
[inData retain];
NSString *urlString = #"http://xyz.com/abcd/kgh.php";
NSURL* url = [NSURL URLWithString:urlString];
NSMutableData *photoData = [[NSMutableData alloc]init];
//SessionID is stored in NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString * boundary = #"photoBoundaryParm";
NSString * boundaryString = [NSString stringWithFormat:#"--%#\r\n", boundary];
NSString * boundaryStringFinal = [NSString stringWithFormat:#"--%#--\r\n", boundary];
[photoData appendData:[boundaryString dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"SessionID\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:[[NSString stringWithFormat:#"SessionID=%#",[defaults objectForKey:#"SessionID"]] dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:[boundaryString dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"photo\";\r\nfilename=\"myphoto.png\"\r\nContent-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:inData];
[photoData appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[photoData appendData:[boundaryStringFinal dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:photoData];
NSString* requestDataLengthString = [[NSString alloc] initWithFormat:#"%d", [photoData length]];
[request addValue:requestDataLengthString forHTTPHeaderField:#"Content-Length"];
[request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary] forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self
startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
[connection start];
[inData release];
inData = nil;
}
Please help.
I m stuck with this for really long time.
Thanks in advance.
try this code, and pass your values in post nsstring
NSString* url=[NSString stringWithFormat:url];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURLURLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60.0];
//do post request for parameter passing
[theRequest setHTTPMethod:#"POST"];
NSString *post = [NSString stringWithFormat:#"&imageData=%#",postData];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
[theRequest setURL:[NSURL URLWithString:url]];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
NSURLConnection *serverConnectionObj = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
this is a class method solution:
header
//=========================
// POST FORM WITH IMG
//=========================
+ (NSData *)postToUrl:(NSURL*)url
form:(NSDictionary*)form
andImage:(UIImage*)img
imageKey:(NSString*)imageKey
error:(NSError**)error
returningResponse:(NSURLResponse**)response;
Class method:
#pragma mark -
#pragma mark POST FORM
//=========================
// POST FORM
//=========================
+(NSData *)postToUrl:(NSURL*)url form:(NSDictionary*)form andImage:(UIImage*)img imageKey:(NSString*)imageKey error:(NSError**)error returningResponse:(NSURLResponse**)response{
NSLog(#"postToUrl:%# Form:%# andImage:%# imageKey:%#",url,form,img,imageKey);
NSString *boundary = #"iOS_iKANIMO_BOUNDARY_STRING";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[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=\"%#\"; filename=\"photo.png\"\r\n", imageKey] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:UIImagePNGRepresentation(img)]];
for (NSString*key in [form allKeys]) {
NSLog(#"%# - %#",key,[form objectForKey:key]);
NSString *value = [form objectForKey:key];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n%#",key, value] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
//Now all we need to do is make a connection to the server and send the request:
[request setHTTPBody:body];
return [NSURLConnection sendSynchronousRequest:request returningResponse:response error:error];
}

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

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";

post image to server in iphone

I want to post/share an image to server from the iphone. Image is ready to share. I am using the way the most sites shows using the below code
NSData *imageData = UIImageJPEGRepresentation(image, 100);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"0x0hHai1CanHazB0undar135";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue: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=\"imageToAttach\"; filename=\"%#\"\r\n",fileName]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: image/jpeg\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];
NSLog(#"%#",returnString);
but it is giving me some internal server error, then i pointed it out that the server is demanding stream bytes of the image..How can i convert the image into stream and then post that stream to server ?
Giving the Same Answer 2 Time.
How to convert image into binary format in iOS?
You can use the CoreGraphics' method UIImagePNGRepresentation(UIImage *image), which returns NSData and save it. and if you want to convert it into again UIImage create it using [UIimage imageWithData:(NSData *data)] method.
- (void)sendImageToServer {
UIImage *yourImage= [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *postLength = [NSString stringWithFormat:#"%d", [imageData length]];
// Init 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:imageData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
// response data of the request
}
[request release];
}
i used this code in my app and it works fine ...
//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");
}
}];
I used this code
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[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];
// add params (all params are strings)
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
// add image data
NSData *imageData = UIImageJPEGRepresentation(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 the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
it works like a charm.
Can you plz see the following code i hope it will be helpful to you.
Here is iOS code
-(void)createConnectionRequestToURL:(NSString *)urlStr withImage:(UIImage*)image withImageName:(NSString*)imageName
{
NSData *imageData = UIImageJPEGRepresentation(image, 90);
NSString *urlString = urlStr;
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [[NSString alloc]init];
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:[#"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\"rn" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/%#.jpg\r\n\r\n",imageName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
//Using Synchronous Request. You can also use asynchronous connection and get update in delegates
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"--------%#",returnString);
}
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}";
}
?>
(OR)
<?php
$request_body = #file_get_contents('php://input');
foreach (getallheaders() as $name => $value)
{
if ($FileName=="FileName")
{
$header=$value;
break;
}
}
$uploadedDir = "directory/";
#mkdir($uploadedDir);
file_put_contents($uploadedDir."/".$FileName.".txt",
$request_body.PHP_EOL, FILE_APPEND);
header('X-PHP-Response-Code: 202', true, 202);
?>
I used this code and it works fine.
If you want more accuracy and speed you can compress the image then upload, but compression is an optional part.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
// RP: Empaquetando datos
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:[NSString stringWithFormat:#"%#",loginoneid] forKey:#"user_id"];
[_params setObject:[NSString stringWithFormat:#"%#",_strpostid] forKey:#"post_id"];
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = #"V2ymHFg03ehbqgZCaKO6jy";
// string constant for the post parameter 'file'
NSString *FileParamConstant = #"files[]";
//RP: Configurando la dirección
NSURL *requestURL = [[NSURL alloc] initWithString:#"http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/"];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
if (imageData) {
printf("appending image data\n");
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\'%#\'; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
NSURLResponse *response = nil;
NSError *err = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
dispatch_async(dispatch_get_main_queue(), ^{
NSString *str = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
I have made block method which you can use all class just create NSObject and for Example you have created
AFClass.h
AFClass.m
So Write this line in your class header file (This is class method so you can simply call by class name as well)
+(NSURLSessionDataTask *)postImageRequestWithURL:(NSString *)URL andParam:(NSDictionary *)param withImages:(NSDictionary *)imageArray response:(void (^)(NSDictionary *posts, NSError *error))block;
And write this code in AFClass.m class
+(NSURLSessionDataTask *)postImageRequestWithURL:(NSString *)URL andParam:(NSDictionary *)param withImages:(NSDictionary *)imageArray response:(void (^)(NSDictionary *posts, NSError *error))block
{
//show Progress hud
[SVProgressHUD showWithStatus:#"Loading..."];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:URL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
for (NSString *strKey in [imageArray allKeys])
{
if ([[imageArray valueForKey:strKey] isKindOfClass:[NSData class]])
{
NSString *strFilename = [NSString stringWithFormat:#"%u.jpg",arc4random()];
[formData appendPartWithFileData:[imageArray valueForKey:strKey] name:strKey fileName:strFilename mimeType:#"image/jpeg"];
}
}
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress)
{
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error)
{
if (error)
{
[SVProgressHUD dismiss];
if (block)
{
block(nil, error);
}
}
else
{
[SVProgressHUD dismiss];
if (block)
{
block(responseObject, nil);
}
}
}];
[uploadTask resume];
return uploadTask;
}
Now I call this class method Here i am giving example
// Set Your URL Here
NSString *strURL = #“Write your URL Here”
// Set Your Post Data Here
NSMutableDictionary *postData = [NSMutableDictionary dictionaryWithDictionary:#{#"user_id”:#“54”,#“first_name”:#“Jignesh”}];
// Here you can send multiple image convert your UIimage to NSData
NSDictionary *profileData = #{#"uploaded_file":UIImageJPEGRepresentation(profilePic,1.0),#"uploaded_file1”:UIImageJPEGRepresentation(profilePic1,1.0)};
Now Call Your class Method for Upload Images
[AFClass postImageRequestWithURL:strURL andParam:postData withImages:profileData response:^(NSDictionary *response, NSError *error)
{
// Here is your Response
}];

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];
}

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];