0

我是 PHP 新手。目前,我正在尝试编写一个 iOS 应用程序并使用 AFNetworking 从该应用程序上传图像。

我有一个这样的 PHP 文件。我可以将图像从 iPad 的 Safari 浏览器上传到我的本地主机。但是,我无法从我的 iOS 应用上传。我该怎么做?

PHP 代码

<?php
//print_r($_FILES);
if(isset($_FILES['image']))
{
    $errors=array();
    $allowed_ext= array('jpg','jpeg','png','gif');
    $file_name =$_FILES['image']['name'];
    $file_ext = strtolower( end(explode('.',$file_name)));

    //print_r($file_ext);

    $file_size=$_FILES['image']['size'];
    $file_tmp= $_FILES['image']['tmp_name'];

    if(in_array($file_ext,$allowed_ext) === false)
    {
        $errors[]='Extension not allowed';
    }

    if($file_size > 2097152)
    {
        $errors[]= 'File size must be under 2mb';

    }
    if(empty($errors))
    {
       if( move_uploaded_file($file_tmp, 'images/'.$file_name));
       {
        echo 'File uploaded';
       }
    }
    else
    {
        foreach($errors as $error)
        {
            echo $error , '<br/>'; 
        }
    }
   //  print_r($errors);

}
?>

<form action="" method="POST" enctype="multipart/form-data">

<p>
    <input type="file" name="image" />
    <input type="submit" value="Upload">

</p>
</form>

iOS 代码

-(void)uploadFile
{

    NSLog(@"gona upload image");
    NSURL *url= [NSURL URLWithString:@"http://192.168.11.7/uploadimage"];
    AFHTTPClient *httpClient= [[AFHTTPClient alloc] initWithBaseURL:url];

    NSData *imageData= UIImageJPEGRepresentation([UIImage imageNamed:@"IMG_2480.jpg"], 0.5);

    //NSLog(@"imageData is %@",imageData);

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

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        NSLog(@"Sent %lld of %lld bytes",totalBytesWritten,totalBytesExpectedToWrite);
    }];

    [httpClient enqueueHTTPRequestOperation:operation];

}
4

1 回答 1

1

可能存在命名问题,请在此处检查您的代码:

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

您的表单接受已发布数据中的“图像”字段,您将其作为“图像数据”发送

于 2013-08-17T10:59:13.623 回答