我正在嘗試執行從iOS應用程序上傳圖像到服務器的簡單任務。但是,運行後我收到以下錯誤消息:將圖像從iOS應用程序上傳到服務器時出錯
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.}
任何想法爲什麼?以下是我的代碼分別爲客戶端和服務器端。
應用端代碼:
-(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"
]);
}
?>
另外添加acceptableContentTypes:「application/html」和「text/plain」。 –
我嘗試了添加這兩種內容類型的建議,但仍然無法使用。這樣的錯誤通常是由於客戶端或服務器端的問題嗎?錯誤消息正在討論的是什麼JSON文本? – Evan
我的意思是說你的回覆不在JSON合成器中。 –