2012-02-19 61 views
0

我試圖通過xcode中的php請求將圖片上傳到我的服務器。我嘗試了很多可能性,但到目前爲止似乎沒有任何工作。我對PHP不太瞭解,所以也許存在這個錯誤。現在它只是給我錯誤「不正確的文件類型」,但我絕對使用JPG圖像。上傳圖片到服務器不起作用

這裏是(與不止一次試了一下)我有什麼在Xcode:

NSData *imageData = UIImageJPEGRepresentation(image.image, 90); 
NSString *urlString = @"http://myserver/upload.php"; 

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

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

NSMutableData *body = [NSMutableData data]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];  
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[NSData dataWithData:imageData]]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[request setHTTPBody:body]; 

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 

和我的PHP文件:

<?php 
$uploaddir = '/images/';  //Uploading to same directory as PHP file 
$file = basename($_FILES['userfile']['name']); 
$uploadfile = $uploaddir . $file; 

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) 
{ 
echo "Temp file uploaded. \r\n"; 
} else { 
echo "Temp file not uploaded. \r\n"; 
} 

if ((!($_FILES['userfile']['type'] == "image/jpeg")) && (!($_FILES['userfile']['type'] == "image/png")))   
{ 
exit("Incorrect file type. " . $_FILES['userfile']['type'] . " is the file type you  uploaded."); 
} 


if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { 
    $postsize = ini_get('post_max_size'); 
    $canupload = ini_get('file_uploads');  
    $tempdir = ini_get('upload_tmp_dir'); 
    $maxsize = ini_get('upload_max_filesize'); 
    echo "http://www.mycompanyname.com/myappname/{$file}" . "\r\n" . $_FILES['userfile']['size'] . "\r\n" . $_FILES['userfile']['type'] ; 
} 

?> 

回答

1

檢查文件類型,並檢查目錄路徑$ uploaddir =「/圖片/」;這是對的嗎?這段代碼對我來說工作正常。

+0

它是?現在這很有趣,爲什麼它不適合我呢?是的,目錄是正確的,絕對是! – Blade 2012-02-19 13:35:32

+0

我只是改變目錄名稱和它的工作,刪除第一個斜槓。 – 2012-02-19 13:37:17

+0

我做到了,他仍然告訴我不正確的文件類型。現在嘗試使用各種圖片,所有圖片都以jpg或png結尾。 – Blade 2012-02-19 14:04:33