PHP Rest API从iOS App接收图像

时间:2015-05-25 20:50:36

标签: php ios objective-c

我是iOS开发的新手,我目前正在开发iOS应用程序,我需要将iOS中的图像发送到用PHP编写的其他API。以下是我将图像发送到PHP服务器的请求在iOS中的样子:

- (void)uploadImage {
    NSString *urlString = @"http://www.private.com/uploadimage.php";
    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0f];
    [urlRequest setHTTPMethod:@"PUT"];

    NSURLSession *session = [NSURLSession sharedSession];

    NSData *imageData = UIImageJPEGRepresentation(self.imageView.image, 0.3f);
    [[session uploadTaskWithRequest:urlRequest fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if(error) {
            NSLog(@"%@",error);
        }
    }] resume];

  }

在我们继续之前,这看起来是否合适?如果它是正确的,我可以编写什么PHP代码来接收正在发送的图像然后将其上传到某个指定的文件夹?我环顾四周,但我还没找到任何处理iOS的NSURLSession的PHP。

1 个答案:

答案 0 :(得分:1)

示例照片上传php代码;

function multiProfileUpload_($target_dir,$files,$user_id)
{
for($i=0; $i < count($files); $i++) {
    $uploadOk = 1;
    $filename = uniqid();
    $imageFileType = pathinfo($files["fileToUpload"]["name"],PATHINFO_EXTENSION);
    $target_file = $target_dir . $filename.".".$imageFileType;
    $name=$filename.".".$imageFileType;

    move_uploaded_file($files["fileToUpload"]["tmp_name"], $target_file);
    $profile_pic = BASE_PATH.$target_dir.$name;
    $query = "UPDATE user_profile SET profile_pic = '$profile_pic' where user_id = $user_id;";
    mysql_query($query);
    $result['status'] = "success";
    $result['path'] = $profile_pic;
}
return $result;
}

Api入口点应该是这样的;

if(@$_REQUEST['apiEntry']=="update_profile_image")
{
    if(!isset($_FILES['fileToUpload']) ||$_FILES['fileToUpload']['error'] == UPLOAD_ERR_NO_FILE)
    {
        $data['status'] = "error";
        $data['message'] = "Error on uploading files";
    }else
    {
        $data = multiProfileUpload_("images/profile/",$_FILES,$_REQUEST['user_id']);
    }
    echo json_encode($data);
}

使用第三方库进行网络连接比使用NSURLConnection本身更方便,因为它们都基于它。示例是使用AFNetworking v2.0

- (void)updateProfileImage{
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   self.user_id,   @"user_id",
                                   nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager alloc] init];
manager.securityPolicy.allowInvalidCertificates = YES;//This is for https
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

[manager POST:[NSString stringWithFormat:@"%@?apiEntry=update_profile_image",BASE_URL] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:UIImageJPEGRepresentation(imgView.image, 1.0f) name:@"fileToUpload" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"%@",operation.request);
    NSDictionary *responseJson = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
    NSLog(@"%@",responseJson);
    if ([[responseJson objectForKey:@"status"] isEqualToString:@"success"]) {
        //do something
    }else{
        //do some other thing
    }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"%@",error);
}];

}