I tried a dozen things. But am not receiving results. I want to convert an audio file wav/mp3 to byte array or otherwise and send it to a php server. Following are few things i tried that are already listed in SO. please help.
NSURL *urlPath = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:#"r2d2" ofType:#"mp3"]];
NSString *wavbundlepath = [urlPath absoluteString];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:wavbundlepath]];
NSUInteger len = data.length;
int8_t *bytes = (int8_t *)[data bytes];
NSMutableString *result = [NSMutableString stringWithCapacity:len];
[result appendString:#"["];
for (NSUInteger i = 0; i < len; i++) {
if (i) {
[result appendString:#","];
}
[result appendFormat:#"%d", bytes[i]];
}
[result appendString:#"]"];
NSString *urlString = #"http://apps2.mobiiworld.com/staging/krafttesting/";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSData* dataSend = [result dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:dataSend];
NSURLResponse *response;
NSError *err;
NSData *responseData2 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData2);
next
NSURL *urlPath = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:#"r2d2" ofType:#"mp3"]];
NSString *wavbundlepath = [urlPath absoluteString];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:wavbundlepath]];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]];
NSString *filename = #"file";
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\";filename=\"%#\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
// NSLog([NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\";filename=\"%#\"\r\n", filename]);
//[body appendData:[[NSString stringWithString:#"test"] dataUsingEncoding:NSUTF8StringEncoding]];
//[body appendData:[[NSString stringWithString:#"\r\n"] 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]];
// 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(#"Return : %#", returnString);
The php developer says that he is not receiving any data whatsoever. And he has echoed whatever he receives, but i find a Null string in response. Can anyone please suggest what to do?
This is how i am doing it
NSData *audioData = Here comes your NSData;
NSString *urlString = #"The url of php file";
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 stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\".caf\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:audioData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"Length : %d", returnData.length);
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Return String %#", returnString);
There is another way via ASIHTTPRequest
NSURL *url = [NSURL URLWithString:#"the url comes here"];
ASIFormDataRequest *formRequest = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
NSData *imageData = UIImageJPEGRepresentation([self scaleAndRotateImage:self.m_ImageViewProfile.image], 90);
NSLog(#"Size : %d", imageData.length);
[formRequest setTimeOutSeconds:600];
[formRequest setPostValue:#"If there is any"] forKey:#"the key"];
[formRequest setData:imageData withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"filename"];
//[formRequest setUploadProgressDelegate:progressView];
[formRequest setCompletionBlock:^{
NSString *responseString = [formRequest responseString];
NSLog(#"Response: %#", responseString);
}];
[formRequest setFailedBlock:^{
NSError *error = [formRequest error];
NSLog(#"Error: %#", error.localizedDescription);
}];
[formRequest startSynchronous];
See if it is what you want
Related
Posting request to .NET server is not working.
NSDictionary *jsonDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSURL *postURL = [NSURL URLWithString: #"SOME URL"];
NSError *error=nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: postURL
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 60.0];
[request setHTTPMethod: #"POST"];
[request setValue: #"application/json" forHTTPHeaderField: #"Accept"];
[request setValue: #"application/json" forHTTPHeaderField: #"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d",[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
The Output is:
{"CreatedBy":"","EmailAddress":"devanrajupericherl#gmail.com","Zipcode":"","FirstName":"devan","DeviceCategoryID:":"","State":"","CustomerTypeID:":"",..........} like this.....
But it Json object must be:
({CreatedBy:"",EmailAddress:"devanrajupericherl#gmail.com",Zipcode:"",FirstName:"devan",DeviceCategoryID::"",State:"",CustomerTypeID:"" })
I am using .Net server for Posting.
Request is not Posting to the Server. Anyone please help me.
NSString *urlString = #"Your Web Service URL";
NSString *parameterString = #"XYZ";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
// parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter_key\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:parameterString dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the 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 %#",returnString);
I am trying to upload the image to json server but url request is going null. Below is the code i am using.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *imageToScale=[info objectForKey:UIImagePickerControllerOriginalImage];
UIImage *img = imageToScale;
//NSLog(#"finalImage---------------------------------%#",self.finalImage);
NSData *imageData = UIImageJPEGRepresentation(img, 0.40);
profileImg = profilePic;
NSArray *arrImg = [profileImg componentsSeparatedByString:#"/"];
NSString *strImg1 = [arrImg objectAtIndex:[arrImg count]-2];
NSString *strImg2 = [arrImg lastObject];
NSLog(#"img2-----------------%#",strImg2);
NSString *pImg = [NSString stringWithFormat:#"%#%#",strImg1, strImg2];
NSLog(#"img-----------------%#",pImg);
NSString *urlString = [NSString stringWithFormat:#"http://www.funnyghg.co/overheadPost.php?userId=%#&type=Photo&text=Demo test&image=%#&location=Chandigarh&Upload=Upload", uid, pImg];
NSLog(#"url :%#", urlString);
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[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"];
/*
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 stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\";filename=\"1.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"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------------%#",returnString);
[self dismissModalViewControllerAnimated:YES];
[appDelegate showAllNavItems];
[appDelegate navFrame];
if([returnString isEqualToString:#"true"])
{
if([profile isEqualToString:#"friend"])
{
[self callServerFriend];
}
if([profile isEqualToString:#"public"])
{
[self callServerPublic];
}
}
}
Please guide for the above. Thanks in advance.
It is because in you code there is an space in urlString between Demo and test. Please remove it as.
Before :
NSString *urlString = [NSString stringWithFormat:#"http://www.funnyghg.co/overheadPost.php?userId=%#&type=Photo&text=Demo test&image=%#&location=Chandigarh&Upload=Upload", uid, pImg];
NSLog(#"url :%#", urlString);
After :
NSString *urlString = [NSString stringWithFormat:#"http://www.funnyghg.co/overheadPost.php?userId=%#&type=Photo&text=Demotest&image=%#&location=Chandigarh&Upload=Upload", uid, pImg];
NSLog(#"url :%#", urlString);
I hope it will work now.
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];
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];
}
I have to upload an image to server for which I wrote code using NSMutableURLRequest like this
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 stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile%#.jpg\"\r\n",self.fileID] 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]];
I guess my PHP script respond corresponding to this and is working fine
how can I replicate above in ASIFormDataRequest?
tried to do this
ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:
[NSURL URLWithString:photoUploadURLString]];
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=\"ipodfile%#.jpg\"\r\n",self.fileID] 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 addData:body withFileName:filename andContentType:#"image/jpeg" forKey:#"snapshot[image]"];
request.uploadProgressDelegate = self.progressView;
[request setDidFinishSelector:#selector(getFacebookPhotoFinished:)];
but didnt got sucess?
here are the details of my PHP scripts
<?php
$uploaddir = './uploads/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "http://example.com/uploads/{$file}";
}
?>
I did as per Cyprian
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"images/ipodfile%#.jpg", fileID]];
NSData *imageData = UIImageJPEGRepresentation([itemImageView image], 0.05);
if (imageData != nil) {
[imageData writeToFile:savedImagePath atomically:YES];
}
if ([[NSFileManager defaultManager] createFileAtPath:savedImagePath contents:imageData attributes:nil])
{
NSLog(#"Image saved");
} else {
NSLog(#"Image not saved");
}
[activityIndicator startAnimating];
NSString *photoUploadURLString = #"http://example.com/imageuploader.php";
NSString* filename = [NSString stringWithFormat:#"ipodfile%#.jpg", self.fileID];
NSLog(#"url is %#/%#",photoUploadURLString, filename);
UIImage *newImage = [[UIImage alloc] init];
newImage=[itemImageView image];
NSURL *url=[NSURL URLWithString:photoUploadURLString];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"userfile" forKey:#"name"];
[request setPostValue:filename forKey:#"filename"];
[request setData:imageData withFileName:filename andContentType:#"image/jpeg" forKey:#"snapshot[image]"];
Uploading file to server using ASIFormDataRequest
-(void)uploadFile{
NSURL *url = [NSURL URLWithString: photoUploadURLString];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setUseKeychainPersistence:YES];
//if you have your site secured by .htaccess
//[request setUsername:#"login"];
//[request setPassword:#"password"];
NSString *fileName = [NSString stringWithFormat:#"ipodfile%#.jpg",self.fileID];
[request addPostValue:fileName forKey:#"name"];
// Upload an image
NSData *imageData = UIImageJPEGRepresentation([UIImage imageName:fileName])
[request setData:imageData withFileName:fileName andContentType:#"image/jpeg" forKey:#"userfile"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(uploadRequestFinished:)];
[request setDidFailSelector:#selector(uploadRequestFailed:)];
[request startAsynchronous];
}
- (void)uploadRequestFinished:(ASIHTTPRequest *)request{
NSString *responseString = [request responseString];
NSLog("Upload response %#", responseString);
}
- (void)uploadRequestFailed:(ASIHTTPRequest *)request{
NSLog(#" Error - Statistics file upload failed: \"%#\"",[[request error] localizedDescription]);
}
Note I was typing from memory so you may have some misspellings.
NSString *strURL = #"enter uerl hear...";
// ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]]; // Upload a file on disk
NSString *filename1=[NSString stringWithFormat:#"friendship.jpg"];
UIImage *image1=[UIImage imageNamed:filename1];
NSData *imageData1=UIImageJPEGRepresentation(image1, 1.0);
[request setData:imageData1 withFileName:filename1 andContentType:#"image/jpeg" forKey:#"avatar"];
[request setRequestMethod:#"POST"];
//[request appendPostData:body];
[request setDelegate:self];
[request setTimeOutSeconds:3.0];
request.shouldAttemptPersistentConnection = NO;
[request setDidFinishSelector:#selector(uploadRequestFinished:)];
[request setDidFailSelector:#selector(uploadRequestFailed:)];
[request startAsynchronous];
- (void)uploadRequestFinished:(ASIHTTPRequest *)request
{
NSLog(#" Error - Statistics file upload failed: \"%#\"",[request responseString]);
}
- (void)uploadRequestFailed:(ASIHTTPRequest *)request{
NSLog(#" Error - Statistics file upload failed: \"%#\"",[[request error] localizedDescription]);
}