2016-12-01 130 views
-1

我想在上傳圖片時更改圖片名稱。上傳時更改圖片名稱

這裏是我的代碼:

if(isset($_POST['submit'])) 
{ 
    $target_dir = "pictures/"; 
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 
    $uploadOk = 1; 
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 

    // Allow certain file formats 
    if($imageFileType != "gif") { 
     echo "Sorry only GIF files are allowed."; 
     $uploadOk = 0; 
    } 
    // Check if $uploadOk is set to 0 by an error 
    if ($uploadOk == 0) { 
     echo "Sorry, your file was not uploaded."; 
    // if everything is ok, try to upload file 
    } else { 
     if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { 
      echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded."; 
      header('Location:field_medal_winner.php'); 
     } else { 
      echo "Sorry, there was an error uploading your file."; 
     } 
    } 
} 

首先我試圖做到這一點蒙山改變move_uploaded_file功能。 但我剛剛得到了其他信息:

if (move_uploaded_file("text.gif", $target_file)) { 
    echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded."; 
} else { 
    echo "Sorry, there was an error uploading your file."; 
} 

有沒有人有一個想法是什麼,我做錯了什麼?

+0

你頭前正在輸出 - 檢查http://php.net/manual/en/function.error-reporting.php和形式的未知。 *「但我剛剛收到其他消息」* - 因爲有錯誤。 –

+0

可能重複的[如何修復]頭文件已發送「PHP中的錯誤」(http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) –

+1

可能[如何重命名上傳的文件,然後將其保存到一個目錄?](http://stackoverflow.com/questions/18705639/how-to-rename-uploaded-file-before-saving-it-into-a-directory ) –

回答

0

替換這些2線

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 

隨着

$target_file = $target_dir . "text.gif"; 
$imageFileType = pathinfo($_FILES["fileToUpload"]["name"],PATHINFO_EXTENSION); 

它將爲保存text.gif在您需要的文件夾。但是,請記住,無論您要上傳哪個文件,它都會覆蓋舊的text.gif文件到text.gif,因爲上傳了具有相同名稱的文件。

更新的代碼

if(isset($_POST['submit'])) 
{ 
    $target_dir = "pictures/"; 
    $target_file = $target_dir . "text.gif"; 
    $uploadOk = 1; 
    $imageFileType = pathinfo($_FILES["fileToUpload"]["name"],PATHINFO_EXTENSION); 

    // Allow certain file formats 
    if(($imageFileType != "gif") || ($imageFileType != "GIF")) { 
    echo "Sorry only GIF files are allowed."; 
    $uploadOk = 0; 
    } 
    // Check if $uploadOk is set to 0 by an error 
    if ($uploadOk == 0) { 
    echo "Sorry, your file was not uploaded."; 
    } else { 
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { 
     echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded."; 
     header('Location:field_medal_winner.php'); 
    } else { 
     echo "Sorry, there was an error uploading your file."; 
    } 
    } 
} 
+0

嘿,只是工作正常坦克爲您的幫助! –

+0

@AaronWerlen:請不要忘記將此答案標記爲正確答案。因爲它可以幫助其他用戶輕鬆找到答案。如果您不知道如何標記答案,那麼請檢查此鏈接。 http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –