簡體   English   中英

將圖像從iOS應用上傳到服務器時出錯

[英]Error with uploading image from iOS app to server

我正在嘗試做一個簡單的任務,將圖像從iOS應用程序上傳到服務器。 但是,運行它后,我收到以下錯誤消息:

錯誤:錯誤域= NSCocoaErrorDomain代碼= 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"
]);
}
?>

好的,抱歉,我意識到這是一個愚蠢的錯誤導致了問題。 僅僅是因為我添加了echo "hello world"; 在php腳本的開頭,導致其觸發JSON文本錯誤。 將其刪除,錯誤消息消失。

不對應於我的問題中所述的錯誤消息,但是代碼中存在的另一個錯誤是我使用了appendPartWithFormData而不是appendPartWithFileData 更改為后者后,可以將圖像上傳到服務器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM