使用AFNetworking和PHP从照片库上传所选图像 [英] Uploading selected image from photo library using AFNetworking and PHP

查看:86
本文介绍了使用AFNetworking和PHP从照片库上传所选图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AFNetworking上传从照片库中选择的图像,但我有点困惑。一些代码示例直接使用图像数据进行上传,而另一些则使用文件路径。我想在这里使用AFNetworking示例代码:

I am trying to upload an image which selected from photo library using AFNetworking but I am little confused. Some code samples are using image data directly for upload and some are using file path. I want to use AFNetworking sample code here:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration 

defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"Success: %@ %@", response, responseObject);
    }
}];
[uploadTask resume];

但是我不知道如何从照片库中获取图像的路径。
谁能告诉我如何从照片库中获取我选择的图像的路径吗?

But I do not know how can I get path of image which I have selected from photo library. Can anyone tell me how can I get path of image which I have selected from photo library?

编辑1:

好​​!我找到以下路径解决方案:

EDIT 1:
OK! I have found following solution for path:

NSString *path = [NSTemporaryDirectory()
                      stringByAppendingPathComponent:@"upload-image.tmp"];
NSData *imageData = UIImageJPEGRepresentation(originalImage, 1.0);
[imageData writeToFile:path atomically:YES];
[self uploadMedia:path];

现在仍然很困惑,因为我在服务器上创建了一个用于上传图像的文件夹。但是,AFNetworking将如何在不访问任何service.php页面的情况下将此图像上传到我的文件夹。只是 http://example.com/upload 就足够了吗?当我尝试上传时,出现以下错误:

Now am still confused becouse I have created a folder for uploaded images on my server. But how AFNetworking will upload this image to my folder without accessing any service.php page. Just http://example.com/upload is enough? When I try to upload I am getting following error:

Error:
Error Domain=kCFErrorDomainCFNetwork
Code=303 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 303.)"
UserInfo=0x1175a970 {NSErrorFailingURLKey=http://www.olcayertas.com/arendi,
    NSErrorFailingURLStringKey=http://www.olcayertas.com/arendi}

编辑2:

好​​。我设法通过以下代码解决错误:

EDIT 2:
OK. I have managed to solve error with following code:

-(void)uploadMedia:(NSString*)filePath {
    NSURLSessionConfiguration *configuration =
    [NSURLSessionConfiguration defaultSessionConfiguration];

    AFURLSessionManager *manager =
        [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSURL *requestURL = 
        [NSURL URLWithString:@"http://www.olcayertas.com/fileUpload.php"];
    NSMutableURLRequest *request = 
        [NSMutableURLRequest requestWithURL:requestURL];

    [request setHTTPMethod:@"POST"];

    NSURL *filePathURL = [NSURL fileURLWithPath:filePath];

    NSURLSessionUploadTask *uploadTask =
        [manager uploadTaskWithRequest:request
                      fromFile:filePathURL progress:nil
             completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
                 if (error) {
                     NSLog(@"Error: %@", error);
                 } else {
                     NSLog(@"Success: %@ %@", response, responseObject);
                 }
             }];

    [uploadTask resume];
}

我正在服务器端使用以下PHP代码上传文件:

I am using following PHP code in server side for uploading file:

<?php header('Content-Type: text/plain; charset=utf-8');

try {

    // Undefined | Multiple Files | $_FILES Corruption Attack
    // If this request falls under any of them, treat it invalid.
    if (!isset($_FILES['upfile']['error']) ||
        is_array($_FILES['upfile']['error'])) {
        throw new RuntimeException('Invalid parameters.');
        error_log("File Upload: Invalid parameters.", 3, "php2.log");
    }

    // Check $_FILES['upfile']['error'] value.
    switch ($_FILES['upfile']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            throw new RuntimeException('No file sent.');
            error_log("File Upload: No file sent.", 3, "php2.log");
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            throw new RuntimeException('Exceeded filesize limit.');
            error_log("File Upload: Exceeded filesize limit.", 3, "php2.log");
        default:
            throw new RuntimeException('Unknown errors.');
            error_log("File Upload: Unknown errors.", 3, "php2.log");
    }

    // You should also check filesize here.
    if ($_FILES['upfile']['size'] > 1000000) {
        throw new RuntimeException('Exceeded filesize limit.');
        error_log("File Upload: Exceeded filesize limit.", 3, "php2.log");
    }

    // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
    // Check MIME Type by yourself.
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search(
        $finfo->file($_FILES['upfile']['tmp_name']),
        array(
            'jpg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
        ), true)) {
        throw new RuntimeException('Invalid file format.');
        error_log("File Upload: Invalid file format.", 3, "php2.log");
    }

    // You should name it uniquely.
    // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
    // On this example, obtain safe unique name from its binary data.
    if (!move_uploaded_file($_FILES['upfile']['tmp_name'], sprintf('./uploads/%s.%s', sha1_file($_FILES['upfile']['tmp_name']), $ext))) {
        throw new RuntimeException('Failed to move uploaded file.');
        error_log("File Upload: Failed to move uploaded file.", 3, "php2.log");
    }

    echo 'File is uploaded successfully.';
    error_log("File Upload: File is uploaded successfully.", 3, "php2.log");

} catch (RuntimeException $e) {
    echo $e->getMessage();
    error_log("File Upload: " . $e->getMessage(), 3, "php2.log");
}

?>

编辑3:

现在,我了解到$ _FILES如何工作。但是,当我运行代码时,却收到成功消息,但是文件没有上传到服务器。知道有什么问题吗?

EDIT 3:
Now I have learned how $_FILES works. How ever when I run my code I am getting success message but file is not uploading to server. Any idea what might be wrong?

推荐答案

使用以下代码

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = info[UIImagePickerControllerOriginalImage];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
[parameters setObject:@"imageUploaing" forKey:@"firstKey"];
NSString *fileName = [NSString stringWithFormat:@"%ld%c%c.jpg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a', arc4random_uniform(26) + 'a'];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSData *data = UIImageJPEGRepresentation(image, 0.5);
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:data name:@"image" fileName:fileName mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

}

这篇关于使用AFNetworking和PHP从照片库上传所选图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆