簡體   English   中英

使用AFNetworking和PHP從照片庫上傳所選圖像

[英]Uploading selected image from photo library using AFNetworking and PHP

我正在嘗試使用AFNetworking上傳從照片庫中選擇的圖像,但我有點困惑。 一些代碼示例直接使用圖像數據進行上傳,而另一些則使用文件路徑。 我想在這里使用AFNetworking示例代碼:

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

但是我不知道如何獲取從照片庫中選擇的圖像路徑。 誰能告訴我如何從照片庫中獲取我選擇的圖像的路徑?

編輯1:
好! 我已經找到以下路徑解決方案:

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就足夠了嗎? 當我嘗試上傳時,出現以下錯誤:

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:
好。 我設法用以下代碼解決了錯誤:

-(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代碼上傳文件:

<?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的工作原理。 但是,當我運行代碼時,卻收到成功消息,但是文件沒有上傳到服務器。 知道有什么問題嗎?

Afnetworking具有通過分段發布的上傳方法。

NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/v1/api" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"filename" fileName:@"file.jpg" mimeType:@"image/jpeg"];
}];

其中imageData是:

UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(originalImage, 1.0);

使用以下代碼

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

}

盡管還有其他上傳圖片的方法,但是如果您想使用您描述的方法,那么在選擇圖片后,您可以獲取其網址,如下所示:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
}

假設您使用UIImagePickerController選擇圖像。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM