I want to upload images in server using ASIHTTPRequest library in my IPhone app.
For image upload, i am using ASIFormDataRequest to upload into server.
I have tried the below codes in my app but it couldn't working and image didn't uploaded in server.
NSURL *url = [NSURL URLWithString:#"http://www.anglerdemo.com/Appln/Aghaven_iphone/Uploadphoto.php"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.requestMethod = #"POST";
NSString *fileName = #"iphone.jpg";
[request addPostValue:fileName forKey:#"name"];
// Upload an image
UIImage *img = [UIImage imageNamed:fileName];
NSData *imageData = UIImageJPEGRepresentation(img, 90);
NSLog(#"imageData ==> %#", imageData);
[request setData:imageData withFileName:fileName andContentType:#"image/jpeg" forKey:#"image"];
[request setDelegate:self];
[request startAsynchronous];
I have tried above codes in my app, request successfully executed and i got the alert message in "requestFinished" delegate method of ASIHTTPRequest. but image didn't uploaded in server.
- (void)requestFinished:(ASIHTTPRequest *)request
{
[[[[UIAlertView alloc]
initWithTitle:#"Message"
message:#"Success!!!"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil]
autorelease]
show];
NSLog(#"success ==> ");
}
I have tried php file script for upload is below.
<?php
$uploaddir = 'upload_files/';
$file = basename($_FILES['image']['name']);
$uploadfile = $uploaddir . $file;
if(move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile))
{
echo "Photo has been saved successfully!…;
}
else {
echo "Failed";
}
?>
Please help in this regards.
Thanks!!!
I think the first thing I would do is add
NSLog(#"%#", [request responseString]);
to requestFinished: just to be sure you see "Failed" being logged. This will prove the problem is with the attempt to call move_upload_file, which I would guess is where things go wrong.
If that's the case, I would be pretty sure that the user your webserver runs as doesn't have write permissions to the upload_files directory.
Related
I have a strange issue using the ASIHTTPRequest library when I attempt to upload images to a php script. I have implemented ASIHTTPRequest correctly, as in the php script does receive the POST data from the iphone simulator, but only for some of the images in my testing set. There are other images that don't pass through the POST.
All images were retrieved from Facebook, and are either jpg or png format. I have tested my code on both types of images, though it shouldn't matter because I use the PNGRepresentation method in my iphone application to convert the image to NSData. I have also tested size of an image, and this is not an issue (ranging from 600x600 to 1200x1200).
The images that break the ASIHTTPRequest don't seem special at all to me, and I am having trouble identifying the bug. Below is some of my implementation:
iPhone Implementation:
[RegisterRequest setData:profilePicturePNG withFileName:filename andContentType:#"image/png" forKey:#"profilePicture"];
[RegisterRequest addRequestHeader:#"Content-Type" value:#"image/png"];
[RegisterRequest setDelegate:self];
[RegisterRequest startAsynchronous];
PHP Implementation:
echo "Upload: " . $_FILES["profilePicture"]["name"] . "<br>";
echo "Type: " . $_FILES["profilePicture"]["type"] . "<br>";
echo "Size: " . ($_FILES["profilePicture"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["profilePicture"]["tmp_name"] . "<br>";
In this test, the PHP implementation should echo the file properties. As I said earlier, for most images I do get an echo back. But there are some images where name and type don't go through and size is reported as 0kb.
Any suggestions? I would greatly appreciate it!
For your info, ASIHTTPRequest is being deprecated, but you can use AFNetworking here you can reference from this.
https://github.com/AFNetworking/AFNetworking and also this example
-(IBAction)uploadButtonClicked:(id)sender{
NSData *imageToUpload = UIImageJPEGRepresentation(mainImageView.image, 90);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://www.THESERVER.com"]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"/PROJECT/upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:#"file" fileName:#"temp.jpeg" mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
[MBProgressHUD hideHUDForView:self.view animated:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[MBProgressHUD hideHUDForView:self.view animated:YES];
if([operation.response statusCode] == 403){
NSLog(#"Upload Failed");
return;
}
NSLog(#"error: %#", [operation error]);
}];
[operation start];
}
I guess for image uploading you should not use ASIHTTPRequest
NSString *requestStr = [yourPHPSCriptURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
responseString = nil;
NSURL *requestUrl = [[NSURL alloc] initWithString:requestStr];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:requestUrl];
[request setPostFormat:ASIMultipartFormDataPostFormat];
[request addPostValue:#".png" forKey:image_content_type]; //Use this if you want//
[request setShouldAttemptPersistentConnection:YES];
[request setData:yourPhotoData withFileName:#"user_image_byte.png" andContentType:#"image/png" forKey:#"user_image_byte"];
[request startSynchronous];
I send my image as byte stream and later in asp.net I convert it back as a image. Hope this helps.
I am using the ASIFormDataRequest for uploading file on server.
I am using ASIHTTPRequest to achieve the functionality of upload in background.
It working fine. But When application going to background then it fail to upload the file.
I try a lot of test with my code, even sometime it works for background too.
When I am uploading file and application going to background and then application again active then it upload successfully.
I notice that (but not sure) if application going in background for time more than the request time out time then it fail to upload. (I am not sure about it)
NSString *filePath = [arguments objectAtIndex:0];
NSString *fileName = [arguments objectAtIndex:1];
NSURL *url = [NSURL URLWithString:#"http://192.168.1.107/~amitb/test/upload.php"];
NSData *imageData = [[[NSData alloc] initWithContentsOfFile:filePath] autorelease];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.delegate = self;
[request setData:imageData withFileName:fileName andContentType:nil forKey:#"file"];
[request startAsynchronous];
Can anybody help me to upload file while application in background
Amit Battan
http://allseeing-i.com/ASIHTTPRequest/How-to-use#background_downloads_ios states that you can use:
[request setShouldContinueWhenAppEntersBackground:YES];
I am developing an app that will request the profile picture URL of some users from Facebook servers, but I don't know how many users I will have (it might be 2 or it might be 20). Should I use ASIHTTPRequest with a loop and a synchronous request, or the API graph (with Facebook SDK for iOS) with a loop?
Trying using ASINetworkQueue. It will allow you to create a queue of ASIHTTPRequests that can still be started asynchronously. For example
- (void)getImages
{
if(!self.queue)
self.queue = [[[ASINetworkQueue alloc] init] autorelease];
NSArray* urlStringsToRequest = [NSArray arrayWithObjects:#"http://www.example.com/image1.png",#"http://www.example.com/image2.png",nil];
for(NSString* urlString in urlStringsToRequest)
{
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestWentWrong:)];
[self.queue addOperation:request];
}
[self.queue go];
}
- (void)requestDone:(ASIHTTPRequest*)req
{
UIImage* image = [UIImage imageWithData:[req responseData]];
[imageArray addObject:image];
}
- (void)requestWentWrong:(ASIHTTPRequest*)req
{
NSLog(#"Request returned an error %#",[req error]);
}
Hello
I am sending some values to the server using ASIHTTPRequest. All works fine until yesterday that the requestFinished didnt work. (when the app send the request on the server an activity indicator and a new view added to the main view and when the request finished is removing the views). I added requestFailed to test if is failed and I get this error:
[3438:207] Error Domain=ASIHTTPRequestErrorDomain Code=2 "The request timed out" UserInfo=0x5ad25c0
Its weird because the same code was working fine yesterday. I am sure that they didnt make any changes on the server's side.
this is the code:
- (IBAction)convert:(id)sender{
//Get the email from the textfield
NSString *email1 = email.text;
//Save the last used email to load it on the next app launch
[[NSUserDefaults standardUserDefaults] setValue:email1 forKey:#"email"];
//Get the current URL from webview
NSString *currentURL= webView.request.URL.relativeString;
lbl.text = currentURL;
//Count the length of Label
int strL= [lbl.text length];
//The url that the requests will be send.
NSURL *url = [NSURL URLWithString:#"the website"];
//Indicator and its view are loading on the screen
[ind startAnimating];
[self.view addSubview:indView];
//ASIHTTPRequests
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
NSString *watch = [lbl.text substringWithRange:NSMakeRange(23,strL-23)];
NSString *link = [NSString stringWithFormat:#"http://youtube.com/%#",watch];
[request setShouldRedirect:YES];
[request setPostValue:watch forKey:#"url"];
[request setPostValue:email1 forKey:#"email"];
[request setPostValue:format forKey:#"format"];
[request setPostValue:quality forKey:#"quality"];
[request setDelegate:self];
[request startAsynchronous];
NSLog(#"%# %# %# %#",watch,email1,format,quality);
click=NO;
}
and this is the requestFinished:
- (void)requestFinished:(ASIFormDataRequest *)request{
NSString *responseString = [request responseString];
NSLog(#"%#",responseString);
NSLog(#"%#",lbl.text);
NSLog(#"requested finished");
[ind stopAnimating];
[indView removeFromSuperview];
[setView removeFromSuperview];
}
Did you try to increase the timeout value on the request? By default it is 10 seconds, you can make it larger by doing this right before the startAsynchronous call:
[request setTimeOutSeconds:60];
I want to upload image on Twitter.
please any one help me how we upload image on Twitter.
Please explain or provide code.
The following is to utilize Twitpic.
As said by others you have to start by looking at the API to understand the requests.
You can use Oliver Drobnik's Tutorial : Uploading UIImages to TwitPic which does it from scratch using NSMutableURLRequest
or you can use the asi-http-request which is a CFNetwork wrapper for HTTP requests
NSData *imageData = UIImagePNGRepresentation(imageToPost);
NSURL *twitpicURL = [NSURL URLWithString:#"http://twitpic.com/api/uploadAndPost"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:twitpicURL] autorelease];
[request setData:imageData forKey:#"media"];
[request setPostValue:#"myUsername" forKey:#"username"];
[request setPostValue:#"myPassword" forKey:#"password"];
[request setPostValue:#"myMessage" forKey:#"message"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestFailed:)];
[request start];
You should look at the first.. first that way you understand what is happening.
You must use a "twitter-picture-provider" like TwitPic or TweetPhoto. They usually provide their own APIs as far as I know.
Twitter does not host image uploads at the moment. You have to use a third-party service. Yfrog and Twitpic are the two most popular on Twitter.
first import twitter frame work after that u write this code
TWTweetComposeViewControllerCompletionHandler completionHandler =^(TWTweetComposeViewControllerResult result)
{
switch (result) {
case TWTweetComposeViewControllerResultCancelled:
NSLog(#"twitter result:cancelled");
break;
case TWTweetComposeViewControllerResultDone:
NSLog(#"twitter result:sent");
}
[self dismissModalViewControllerAnimated:YES];
};
TWTweetComposeViewController *tvc = [[TWTweetComposeViewController alloc] init];
if(tvc)
{
[self addTweetContentContent:tvc];
tvc.completionHandler = completionHandler;
[self presentModalViewController:tvc animated:YES];
}
the local method is....
-(void)addTweetContentContent:(id)tvc
{
UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImagePNGRepresentation(image1);
UIImage *picture = [UIImage imageWithData:imageData];
or
UIImage *picture=[UIImage imageNamed:#"a.png"];
[tvc addImage:picture];
NSString *tweetText = #"write your comands";
[tvc setInitialText:tweetText];
}