AFNetworking Uploading Image

2019-03-11 06:14发布

问题:

I've look at a few examples but I think my problem may be with in the PHP. I am trying to upload an image to a server from the iphone using AFNetworking. Here is my obj-c code:

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

This is my upload.php:

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;

}

When I try to upload it fails at

if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {

and returns the 403 / false status code that I set

回答1:

It was a silly mistake...

in php i needed

$uploaddir = 'uploads/';

instead of

$uploaddir = '/uploads/';