2011-06-03 106 views
1

我想從我的iPhone應用上傳一個plist文件到我的服務器。我嘗試了下面的代碼(發現谷歌搜索),但我的文件仍然沒有上傳。哪裏有問題?iPhone上的文件上傳問題

iPhone應用程序代碼(方法,可處理上傳):服務器

- (IBAction)sendHTTPPost:(id)sender { 

    NSString *path = [self pathOfFile]; 
    NSString *fileName = @"Contacts"; 
    NSData *data = [[NSData alloc] initWithContentsOfFile:path]; 
    NSString *urlString = @"http://localhost/ajaxim/fileUpload.php"; 

    //set up request 
    NSMutableURLRequest *request= [[[NSMutableURLRequest alloc] init] autorelease]; 
    [request setURL:[NSURL URLWithString:urlString]]; 
    [request setHTTPMethod:@"POST"]; 

    //required xtra info 
    NSString *boundary = @"---------------------------14737809831466499882746641449"; 
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; 
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; 

    //body of the post 
    NSMutableData *postbody = [NSMutableData data]; 
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", fileName] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postbody appendData:data]; 
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [request setHTTPBody:postbody]; 

    //lets make the connection 
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 
    returnString = [returnString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
    //NSLog(returnString); 
    } 

PHP代碼:

<?php 
$target = "./upload/"; 
$target = $target . basename($_FILES['uploaded']['name']) ; 
$ok=1; 
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) 
{ 
    echo "YES"; 
    echo "http://localhost/ajaxim/upload/{$target}"; 
} 
else { 
    echo "Not uploaded"; 
} 
?> 

,請給我一些建議,我應該在哪裏修改代碼或者我錯了?

回答

2

在我看來,您正在以userfile的身份發佈文件,並試圖將其讀取爲uploaded

使這種制服,它應該工作。

+0

我已經改變了它

喬敦 - R的人YourDirectoryName
搭配chmod -R 755 YourDirectoryName ..bt它不工作.. :( – Shahriar 2011-06-03 08:28:49

+0

你可以檢查你的'$ _POST'和'$ _FILES'數組嗎?這是否提供線索? – sergio 2011-06-03 08:39:22

0

我知道這是一個有點晚:

我沒有看到你給我們您所使用的服務器的類型。

如果使用unix或linux服務器。包括我自己在內的許多人忘記檢查您使用的目錄的權限。 您想確保您具有添加,移動和刪除文件的適當權限。

這可以通過導航到包含文件夾上傳你的shell並運行以下命令的目錄安全進行: