2012-06-04 108 views
12

我看了幾個例子,但我認爲我的問題可能與在PHP中。我試圖從iphone上使用AFNetworking將圖像上傳到服務器。這裏是我的OBJ-C代碼:AFNetworking上傳圖片

-(IBAction)uploadButtonClicked:(id)sender 
{ 

NSData *imageToUpload = UIImageJPEGRepresentation(mainImageView.image, 90); 
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://www.THESERVER.com"]]; 

NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"/PROJECT/upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { 
    [formData appendPartWithFileData: imageToUpload name:@"file" fileName:@"temp.jpeg" mimeType:@"image/jpeg"]; 
}]; 

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSString *response = [operation responseString]; 
    NSLog(@"response: [%@]",response); 
    [MBProgressHUD hideHUDForView:self.view animated:YES]; 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    [MBProgressHUD hideHUDForView:self.view animated:YES]; 
    if([operation.response statusCode] == 403){ 
     NSLog(@"Upload Failed"); 
     return; 
    } 
    NSLog(@"error: %@", [operation error]); 

}]; 

[operation start]; 
} 

這是我的upload.php的:

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

    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) { 
     sendResponse(200, 'Upload Successful'); 
     return true; 
    } 
    sendResponse(403, 'Upload Failed'); 
     return false; 

} 

當我試圖把它上傳失敗在

if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) { 

,並返回403 /假我設置的狀態代碼

+0

最有可能的權限問題。啓用'error_reporting(E_ALL)' –

+0

因爲我正在通過iOS設備執行此操作,所以我如何傳回錯誤消息?我有一個我可以使用的函數sendResponse('400',「$ errors」),但是我該如何設置$ errors? – mkral

+0

@mkral:我知道這是有點老,但我試圖實現上傳部分的代碼的修改版本,它並沒有爲我工作 它到底是否爲你工作? ps im試圖學習ios/objective C –

回答

3

這是一個愚蠢的錯誤...

在PHP我需要

$uploaddir = 'uploads/'; 

,而不是

$uploaddir = '/uploads/'; 
+0

嘿,我用你的代碼,但是我得到了「response:[(null)]」,你能幫我嗎? thanx – AliBZ

+0

最有可能意味着您的網絡服務出現錯誤,或者它沒有返回任何JSON – mkral

+0

是否可以向我發送代碼的上傳部分?我一直在尋找過去兩天的實例。 Thanx – AliBZ