2016-12-01 96 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 –