将图像从iOS应用程序上传到服务器时出错

时间:2015-12-26 09:52:42

标签: php ios server

我正在尝试从iOS应用程序上传图像到服务器的简单任务。但是,我在运行它后收到以下错误消息:

  

错误:错误Domain = NSCocoaErrorDomain Code = 3840“JSON文本没有以数组或对象和选项开头,以允许未设置片段。” UserInfo = {NSDebugDescription = JSON文本不以数组或对象开头,并且选项允许未设置片段。}

知道为什么吗?以下是我的客户端和服务器端代码。

应用程序端代码:

-(void) uploadPhoto: (UIImage*) image{
    NSString *urlString = @"myServerDNS.com/upload.php";

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

    NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
    NSDictionary *parameters = @{@"foo":@"bar"};
    [manager POST:urlString
       parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {[formData appendPartWithFormData:imageData name:@"file"];}
          success:^(AFHTTPRequestOperation *operation, id responseObject)
    {NSLog(@"Success: %@", responseObject);}
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {NSLog(@"Error: %@", error);}
     ];
}

服务器端php代码:

<?php
$foo = $_POST["foo"];

$target_dir = "Folder/" . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) 
{
echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK"
]);

} else {
echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error"
]);
}
?>

1 个答案:

答案 0 :(得分:0)

好的,对不起,我意识到导致这个问题是一个愚蠢的错误。这只是因为我在php脚本的开头添加了echo "hello world";,导致它触发JSON文本错误。删除它,错误消息消失了。

与我的问题中陈述的错误消息不对应,但我的代码中存在的另一个错误是我使用了appendPartWithFormData而不是appendPartWithFileData。更改为后者后,图像上传到服务器工作。