2016-08-16 77 views
1

我正在php web應用程序中使用以下代碼從本地機器上傳服務器上的文件。上傳的文件在php中不起作用

 <form action="upload.php" method="post" enctype="multipart/form-data"> 
     Select file to upload: 
     <input type="file" name="fileToUpload" id="fileToUpload" value="c:/passwords.txt"> 
     <input type="submit" value="Upload" name="submit"> 
     </form> 

upload.php的

$target_dir = "uploads/"; 
     $target_file = $target_dir .basename($_FILES["fileToUpload"]["name"]); 
     $uploadOk = 1; 



     if ($_FILES["fileToUpload"]["size"] > 5000000) { 
      echo "Sorry, your file is too large."; 
      $uploadOk = 0; 
     } 


     if ($uploadOk == 0) { 
      echo "Sorry, your file was not uploaded."; 
      // if everything is ok, try to upload file 
     } else { 
     echo $_FILES['fileToUpload']['name']."<br>";  
     if(move_uploaded_file($_FILES["fileToUpload"]["name"], $target_file)) {  
      echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded."; 
      } else { 
      echo "Sorry, there was an error uploading your file."; 
      } 
     } 

但上面的代碼是行不通的。我查了上傳文件夾的權限

drwxrwxrwx 2 ankit ankit 4096 Aug 2 13:41 uploads 

這似乎是可寫的。我改變了我的項目許可使用以下命令

sudo chmod -R 777 /var/www/myproject 

但我仍然無法上傳服務器上的文件。我可以知道我錯在哪裏嗎?

+0

你有你的榜樣輸出消息? –

+0

輸出消息:抱歉,上傳文件時出錯。 –

+0

將$ target_dir路徑更改爲完整路徑並查看它是否有效。出於安全目的,也使用775權限而不是777。 – Ionut

回答

4

在您的意見你說你得到error1當您使用

print_r($_FILES); 

這是由於

1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini', 

所以做這個

upload_max_filesize = 'Size'; // whatever you want 

Documentation about $_FILES errors

+0

我收到「抱歉,上傳文件時出現錯誤。」 –

+0

@ user1234正在討論'print_r($ _ FILES)'錯誤;' –

+0

我可以通過更改upload_max_filesize ='Size'參數來解決此問題。 –

3

改變這一行:

$_FILES["fileToUpload"]["name"] // contains the original name of the uploaded file from the user's computer 

$_FILES["fileToUpload"]["tmp_name"] // tmp_name will contain the temporary file name of the file on the server 

的文檔move_uploaded_file。你想移動上傳文件! ;-)

它會幫助你

+0

我做到了,但它似乎沒有工作。事實上,當我打印$ _FILES [「fileToUpload」] [「tmp_name」]沒有輸出,這意味着這個變量不存在。 –

+0

嘗試print_r($ _ FILES)並檢查它是否可用? –

+0

info:Array ( [fileToUpload] => Array ( [name] => data。XLSX [型] => [tmp_name的值] => [錯誤] => 1 [尺寸] => 0 ) )如果沒有tmp_name的值 –

2

move_uploaded_file預計參數一個是源,這是tmp_name

所以更改

if(move_uploaded_file($_FILES["fileToUpload"]["name"], $target_file)) { 

if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { 
+0

如何解決這個問題,如果沒有tmp_name或損壞的文件? –

+0

我在這個鏈接找到類似的問題,http://stackoverflow.com/questions/14472741/files-field-tmp-name-has-no-value-on-jpg-file-extension,請參考給出的答案通過#staticsan。 – ameenulla0007