簡體   English   中英

使用AFNetworking 2和Slim PHP框架無法上傳圖像

[英]Failing to upload image with AFNetworking 2 and Slim PHP framework

這是我的瘦框架PHP代碼

    $app->post('/uploadPicture', function () {

    if (!empty($_FILES)) {

        global $config;
        $picturePath = $config->get('db', 'picture');

        $allowedExts = array("jpg", "jpeg", "png");
        $extension = end(explode(".", $_FILES["file"]["name"]));

        if ($_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "image/png" && $_FILES["file"]["size"] < 2500000 && in_array($extension, $allowedExts)) {

            if ($_FILES["file"]["error"] > 0) {

                echo "Error: " . $_FILES["file"]["error"] . "<br />";
            } else {

                if (move_uploaded_file($_FILES['file']['tmp_name'], $picturePath . $_FILES["file"]["name"])) {
                    echo "success";
                }

            }
        } else {

            echo "Invalid file type";
        }
    } else {

        echo "no file to upload";
    }

});

這就是我在iPhone手機上使用的。

    -(void)uploadImage:(UIImage *)image withPersistentID:(NSString *)persistentID {

    [[MSMAMobileAPIClient sharedClient] POST:@"uploadPicture" parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData) {

        NSData *imageData = UIImageJPEGRepresentation(image, 90);

        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", persistentID];

        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg"];

    } success:^(NSURLSessionDataTask * task, id responderData) {

        self.itemImageBlock(YES);

    } failure:^(NSURLSessionDataTask * task, NSError * error) {

        NSLog(@"%@",[error.userInfo objectForKey:@"JSONResponseSerializerWithDataKey"]);
        self.itemImageBlock(NO);

    }];

}

在iPhone的一面,它似乎像服務器一樣忙,然后最終因超時而失敗。

我一直在使用CocoaRestClient並且能夠上傳圖像。

我還看到在嘗試從iphone上傳時,文件被添加到php的臨時目錄中。

難道我做錯了什么?

編輯:我剛剛在uploadPicture函數中添加了一個錯誤日志行,它看起來好像是首先被iphone調用了! :(

EDIT2:這是返回錯誤消息的NSLog

Error: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x17d6e1c0 {NSErrorFailingURLStringKey=https://192.168.1.15/mamobile/index.php/uploadPicture, NSErrorFailingURLKey=https://192.168.1.15/mamobile/index.php/uploadPicture, NSLocalizedDescription=The request timed out., NSUnderlyingError=0x17db1460 "The request timed out."}

編輯3:我刪除了苗條的PHP框架,只是創建了一個只上傳圖片的簡單PHP腳本。

<?php 


if (!empty($_FILES)) {

    //load configuration file
    require_once 'Lite/Lite.php';
    $config = new Config_Lite('config.ini');
    $picturePath = $config->get('db', 'picture');

        $allowedExts = array("jpg", "jpeg", "png");
        $extension = end(explode(".", $_FILES["file"]["name"]));

        if ($_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "image/png" && $_FILES["file"]["size"] < 2500000 && in_array($extension, $allowedExts)) {

            if ($_FILES["file"]["error"] > 0) {

                echo "Error: " . $_FILES["file"]["error"] . "<br />";
            } else {

                if (move_uploaded_file($_FILES['file']['tmp_name'], $picturePath . $_FILES["file"]["name"])) {
                    echo "success";
                }

            }
        } else {

            echo "Invalid file type";
        }
    } else {

        echo "no file to upload";
    }

?>

然后我改變了我的代碼以這種方式工作。

NSString *urlString = [NSString stringWithFormat:@"https://%@/mamobile/uploadPicture.php", [[NSUserDefaults standardUserDefaults] stringForKey:@"serviceIPAddress"]];
    AFHTTPSessionManager *imageSession = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:urlString]];
    imageSession.responseSerializer = [MSJSONResponseSerializerWithData serializer];
    [imageSession.requestSerializer setAuthorizationHeaderFieldWithUsername:@"fake username" password:@"fake password"];
    [imageSession.securityPolicy setAllowInvalidCertificates:YES];

    [imageSession POST:@"" parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData) {

        NSData *imageData = UIImageJPEGRepresentation(image, 90);

        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", persistentID];

        NSLog(@"uploading image '%@' with size = %@",fileName,[NSByteCountFormatter stringFromByteCount:imageData.length countStyle:NSByteCountFormatterCountStyleFile]);

        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg"];

    } success:^(NSURLSessionDataTask * task, id responderData) {
        NSLog(@"Success: %@", responderData);
        self.itemImageBlock(YES);

    } failure:^(NSURLSessionDataTask * task, NSError * error) {
        NSLog(@"Error: %@",error);
        self.itemImageBlock(NO);

    }];

但我仍然得到相同的超時消息。 所以它與苗條的php框架無關。

您收到的錯誤是: The request timed out.

這意味着,從移動設備上傳到PHP腳本的圖像花費的時間超過PHP上腳本執行時間配置的最大設置。

要解決此問題,您可以在PHP腳本的開頭添加:

<?php 

// Allow script to run longer
set_time_limit(600); // in seconds, set it to 0 to run forever until completion

// Proceed with upload
if (!empty($_FILES)) {
    ...
}

https://github.com/AFNetworking/AFNetworking/issues/1510#issuecomment-29687300

有一個問題我也很相似。 解決方案是從以下代碼添加。

[formData appendPartWithFormData:[[NSNumber numberWithInt:imageData.length].stringValue dataUsingEncoding:NSUTF8StringEncoding] name:@"filelength"];

暫無
暫無

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

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