我想在上传时更改图片名称。
这是我的代码:
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 :(得分:0)
替换这两行
$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.";
}
}
}