简体   繁体   English

使用AFNetworking 2和Slim PHP框架无法上传图像

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

Here's my slim framework php code 这是我的瘦框架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";
    }

});

This is what I'm using on the iphone side. 这就是我在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);

    }];

}

on the iphone side it just seems to hang like the server is busy and then it eventual fails with a timeout. 在iPhone的一面,它似乎像服务器一样忙,然后最终因超时而失败。

I've been using CocoaRestClient and am able to upload the image. 我一直在使用CocoaRestClient并且能够上传图像。

I also see the files being added to php's temp directory when attempting an upload from an iphone. 我还看到在尝试从iphone上传时,文件被添加到php的临时目录中。

Am I doing something wrong? 难道我做错了什么?

EDIT: I just added an error log line to the uploadPicture function and it doens't even seem like it's being called by the iphone in the first place! 编辑:我刚刚在uploadPicture函数中添加了一个错误日志行,它看起来好像是首先被iphone调用了! :( :(

EDIT2: Here's the NSLog with the error message returned 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."}

EDIT3: I eliminated the slim php framework and just created a simple php script that only uploads a picture. 编辑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";
    }

?>

Then I changed my code to work this way. 然后我改变了我的代码以这种方式工作。

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

    }];

But I still get the same timeout message. 但我仍然得到相同的超时消息。 So it has nothing to do with the slim php framework. 所以它与苗条的php框架无关。

The error you are getting is : The request timed out. 您收到的错误是: The request timed out.

This means, the image you are uploading from mobile to PHP script is taking longer than the max setting for script execution time config on your PHP. 这意味着,从移动设备上传到PHP脚本的图像花费的时间超过PHP上脚本执行时间配置的最大设置。

To fix this, you can add this at the beginning of your PHP script: 要解决此问题,您可以在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 https://github.com/AFNetworking/AFNetworking/issues/1510#issuecomment-29687300

There is a problem I also similar. 有一个问题我也很相似。 Solution is to add from the following code. 解决方案是从以下代码添加。

[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