2014-12-24 18 views
4

我使用AFNetworking嘗試上傳文件:上傳源碼文件

-(void)uploadFile{ 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"data.sqlite"]; 
    NSURL *filePathURL = [NSURL fileURLWithPath:filePath]; 

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://localhost:8888/myApp/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
     [formData appendPartWithFileURL:filePathURL name:@"file" fileName:@"data.sqlite" mimeType:@"text/html" error:nil]; 
    } error:nil]; 

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
    NSProgress *progress = nil; 

    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
     if (error) { 
      NSLog(@"Error: %@", error); 
     } else { 
      NSLog(@"Success: %@ %@", response, responseObject); 
     } 
    }]; 

    [uploadTask resume]; 
} 

而這個php文件upload.php

<?php 

    $uploaddir = 'uploads/'; 
    $file = basename($_FILES['uploadedfile']['name']); 
    $uploadfile = $uploaddir . $file; 

    echo "file=".$file; 

    if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile)) { 
     echo $file; 
    } 
    else { 
     echo "error"; 
    } 
    ?> 

這是印刷:

誤差區域= com.alamofire.error.serialization.response代碼= -1016 「請求失敗:不可接受的內容類型:文本/ HTML」 UserInfo = 0x7b8b2bf0

問題來自mimeType?我還在iOS和PHP兩側使用了application/x-sqlite3內容類型。

+0

您在上傳文件時需要一個有效的加密類型。 –

+0

@ Fred-ii-在我的情況下,什麼可能是「有效的」? – androniennn

+0

我沒注意到你在使用'但是AFMultipartFormData'了'文/ html'是困擾我的一部分。通常,多部分的二手什麼,但你的情況,我想嘗試用'文本替換'文/ html'/plain'嘗試,看看它說。 –

回答

5

客戶端代碼使用file字段名正在上傳,但服務器代碼正在查找uploadedfile。您必須在兩個平臺上使用相同的字段名稱。

的mime類型應該是固定的。由於SQLite的文件是二進制文件,而不是文本文件,我建議的application/x-sqlite3application/octet-stream,而不是text/htmltext/plain一個MIME類型。但是,不匹配的字段名稱是更爲嚴重的問題。


順便說一句,你報告一個錯誤信息:

錯誤域= com.alamofire.error.serialization.response代碼= -1016「請求失敗:無法接受的內容類型:文本/ HTML」的UserInfo = 0x7b8b2bf0

這通常是在你的服務器頁面返回text/html的結果,而是AFURLSessionManager期待JSON。

可以更改經理responseSerializer

manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 

或者,更好的,改變你的服務器代碼返回JSON。

+1

*「因爲SQLite文件是二進制文件,而不是文本文件」* - 啊,直到現在我還不知道。我之前並不想給OP提供關於將其改爲「text/plain」的錯誤信息,這是我的錯誤。我會記得那一個。 –

+0

非常感謝Rob,你總是在這裏幫助我們。我現在有了一個「成功」的迴應,這完全是邏輯。謝謝你,接受! – androniennn