0

我想要做的是,当用户上传文件时,它使用变量的值作为文件名,而不是实际的文件名,然后将其保存为该名称。

因此,例如,如果变量是$variable = "50";,我如何将文件另存为50.png(或他们上传的任何扩展名)?

这是我的代码:

$variable = $_POST['id']; // taken from the form

$whitelist = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 2097152) && in_array($extension, $whitelist)) {
  if($_FILES["file"]["error"] > 0) {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
  } else {
    echo "File name: " . $_FILES["file"][$user_id];

    if(file_exists("upload/" . $_FILES["file"]["name"])) {
      echo $_FILES["file"]["name"] . " already exists. ";
    } else {
      move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    }
  }
} else {
  echo "Invalid file";
}

请帮忙。

4

3 回答 3

0

在你的线上

move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);

更改文件名。

$filenameAltered = '50.png';
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $filenameAltered);
于 2013-09-09T22:41:05.417 回答
0

您可以使用其他变量或覆盖现有值。在文件顶部添加此行:

$_FILES["file"]["name"]='50.png';
于 2013-09-09T22:43:45.040 回答
0
$variable = $_POST['id']; // taken from the form

$whitelist = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 2097152) && in_array($extension, $whitelist)) {
  if($_FILES["file"]["error"] > 0) {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
  } else {
    echo "File name: " . $_FILES["file"][$user_id];

    **$name2= $variable.".".$extension;**

    if(file_exists("upload/" . $_FILES["file"]["name"])) {
      echo $_FILES["file"]["name"] . " already exists. ";
    } else {
      **move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $name2);**
      echo "Stored in: " . "upload/" . $name2;
    }
  }
} else {
  echo "Invalid file";
}
于 2013-09-10T04:26:57.750 回答