我想知道是否有人可以帮我解决这个问题。我希望能够使用PHP将图片上传到用户导演,但我希望它将默认名称更改为avatar.whatever。这是我到目前为止的代码,它只是稍微修改过的w3schools版本:
<?php
session_start();
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["avatar"]["name"]));
if ((($_FILES["avatar"]["type"] == "image/gif")
|| ($_FILES["avatar"]["type"] == "image/jpeg")
|| ($_FILES["avatar"]["type"] == "image/jpg")
|| ($_FILES["avatar"]["type"] == "image/pjpeg")
|| ($_FILES["avatar"]["type"] == "image/x-png")
|| ($_FILES["avatar"]["type"] == "image/png"))
&& ($_FILES["avatar"]["size"] < 100000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["avatar"]["error"] > 0)
{
echo "Return Code: " . $_FILES["avatar"]["error"] . "<br \>";
}
else
{
echo "Upload: " . $_FILES["avatar"]["name"] . "<br>";
echo "Type: " . $_FILES["avatar"]["type"] . "<br>";
echo "Size: " . ($_FILES["avatar"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["avatar"]["tmp_name"] . "<br>";
$home_dir = "users/" . $_SESSION["user"] . "/";
if (file_exists($home_dir . $_FILES["avatar"]["name"]))
{
echo $_FILES["avatar"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["avatar"]["tmp_name"],$home_dir . $_FILES["avatar"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["avatar"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
表单部分工作正常,我会删除if语句,检查文件是否已经存在但输出不多,但有人可以帮我弄清楚如何设置预定义的文件名。用户可以选择图片文件然后上传到他们的目录。谢谢
答案 0 :(得分:0)
该行:
move_uploaded_file($_FILES["avatar"]["tmp_name"],$home_dir . $_FILES["avatar"]["name"]);
将使用第二个参数重命名该文件:
move_uploaded_file($_FILES["avatar"]["tmp_name"],"/path/to/image_predefined_name.jpg");
将使用名称image_predefined_name.jpg保存它。
答案 1 :(得分:0)
move_uploaded_files()
函数(在代码的最后)接受两个参数:文件的临时位置和名称,以及所需的位置和名称。目前,您正在这样做:
move_uploaded_file($_FILES["avatar"]["tmp_name"],$home_dir . $_FILES["avatar"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["avatar"]["name"];
其中存储名称为$_FILES["avatar"]["name"]
的文件(用户的文件名)。只需将其替换为您想要的名称:$home_dir . "the name i want.whatever"
。