0

I have searched a lot for a working uploading code using AFNetwork but no luck. I came up with this code which I got it from 2 different sites:

NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"1.png"]);
NSURL *url = [NSURL URLWithString:@"http://localhost/project"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData name:@"google" fileName:@"1.png" mimeType:@"image/png"];
}];


AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"IP Address: %@", [JSON valueForKeyPath:@"origin"]);
} failure:nil];

[operation start];

But what I get is "IP Address: (null)". My php side is this:

function upload(){
$uploaddir = 'uploads/';
$file = basename($_FILES['file']['name']);
$uploadfile = $uploaddir . $file;

if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
    sendResponse(200, 'Upload Successful');
    return true;
}
sendResponse(403, 'Upload Failed');
    return false;
}

I really appreciate a little help.

AliBZ
  • 4,039
  • 12
  • 45
  • 67

2 Answers2

3

I've made this just some days ago. Code on the iPhone side (it uploads an image and another text parameter, item)

NSString *uploadURL = @"http://www.baseurl.it/";
NSURL *url = [[NSURL alloc]initWithString:uploadURL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
NSDictionary *dict = [NSDictionary
                      dictionaryWithObjects:@[self.itemValue]
                      forKeys:@[@"item"]];
// self.itemValue is a post parameter type nsstring

NSURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"path/to/page.php" parameters:dict constructingBodyWithBlock: ^(id <AFMultipartFormData> formData) {
// self.itemData is an NSData containing the image
    if (self.itemData)
        [formData appendPartWithFileData:self.itemData name:@"imageData" fileName:@"imageData.jpg" mimeType:@"image/png"];
}];

// sorry for the formatting here, is a long method using blocks
AFJSONRequestOperation *json = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                                               success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){
                                                                                   NSLog(@"Upload Success");
                                                                               }                                                                                   
                                    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                                                                                   NSLog(@"Error: %@", error.description);

                                                                               }];
[json start];

On the Php side:

// file upload
try {
$fileName = $_FILES['imageData']['name'];
$tmpName  = $_FILES['imageData']['tmp_name'];
$fileSize = $_FILES['imageData']['size'];
$fileType = $_FILES['imageData']['type'];

$fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);

if(!get_magic_quotes_gpc())
{
    $fileName = addslashes($fileName);
}

} catch (Exception $e) {
    echo json_encode("Error:".$e);
}

// $content contains your image

Not sure if it's error free, because it has been taken from a longer source, so I've modified some pieces of code

LombaX
  • 17,265
  • 5
  • 52
  • 77
  • Thanx for the code, Just one thing, when i test my php code using html browse, i have this: and my image name is 1.png. I have a problem with setting itemData and dict using these. Could you help me with it? – AliBZ Nov 02 '12 at 22:48
  • You simply have to convert your UIImage in NSData. You can do with self.itemData = UIImagePNGRepresentation(yourUIImageInstance); . In my code self.itemData is a Property type NSData. – LombaX Nov 02 '12 at 22:48
  • Can you explain again? I don't understand your problem now. If you want to check your php code using browser, you have to make one simple page with a form and an input type file (the line you have posted). The form method is post and the action is the address of the php receiver page.
    then simply select the file and upload
    – LombaX Nov 02 '12 at 22:57
  • Sorry about that, I checked it with the browser and its ok. Now I want to know how to replace my variables with yours. Like in this code: NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[self.itemValue] forKeys:@[@"item"]]; I want to know what self.itemValue and item are so I could replace them. Same thing for: [formData appendPartWithFileData:self.itemData name:@"imageData" fileName:@"imageData.jpg" mimeType:@"image/png"]; – AliBZ Nov 02 '12 at 23:01
0

Check out my answer to a similar question. I use this custom class (written by me( for all my remote web-service operations. It is flexible enough to allow additional POST params to be send along with the image file data. The processFileUploadRequestWithURL method is the one you will need, the others you may use or not.

SO Post Here

Community
  • 1
  • 1
LJ Wilson
  • 14,445
  • 5
  • 38
  • 62