duan20081202 2015-12-26 09:52
浏览 50

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

I am trying to do a simple task of uploading an image to server from iOS app. However I am receiving the following error message after running it:

Error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

Any idea why? The following is my code for client side and server side respectively.

App side code:

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

Server side php code:

<?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条回答 默认 最新

  • doufei2662 2015-12-27 04:50
    关注

    Okay, sorry I realised it was a stupid mistake causing the problem. It was simply because I added an echo "hello world"; at the start of the php script, causing it to trigger the JSON text error. Removed it and the error message went away.

    Not corresponding to the error message stated in my question, but another bug that exists in my code was that I used appendPartWithFormData instead of appendPartWithFileData. After changing to the latter, image upload to server works.

    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算