【问题标题】:PHP file upload - rename filePHP文件上传 - 重命名文件
【发布时间】:2021-10-25 14:22:08
【问题描述】:

使用www.w3schools.com/php/php_file_upload.asp 作为基础,我想上传一个文件,但更改文件名以在我的表单中包含一个字段,加上特定的测试。

我该怎么做? (我对此很陌生)

EG。正在上传的文件名 = TestFile.jpeg

我希望将文件重命名为 [表单中的名字字段]_invoice.jpeg

这是我的表格:

 <form action="upload.php" method="post" enctype="multipart/form-data">
First name
<input type="text" name="first_name" id="first_name" />

  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
</form>

这是我的 PHP:

    <?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
  echo "Sorry, your file is too large.";
  $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "pdf"  && $imageFileType != "txt"  && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
  echo "Sorry, only PDF, TXT, JPG, JPEG, PNG & 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 ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
  } else {
    echo "Sorry, there was an error uploading your file.";
  }
}
?>

【问题讨论】:

  • 文件通过move_uploaded_file“重命名”(实际上,这会将文件从临时目录移动到指定的目标)-然后在$target_file中创建您想要的文件名。
  • 比如$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]) . $_POST['first_name'];

标签: php html forms file-upload


【解决方案1】:

像这样更改代码中的第一行:

<?php
$target_dir = "uploads/";
$imageFileType = strtolower(pathinfo($_FILES["fileToUpload"]["name"],PATHINFO_EXTENSION));
$target_file = $target_dir . trim($_POST['your_name']) . '_invoice.' . $imageFileType;
$uploadOk = 1;

但您还必须在表单中包含&lt;input type="text" name="your_name"&gt;,因为根据您的代码和the article,没有文本输入。

【讨论】:

    猜你喜欢
    • 2016-02-28
    • 2012-05-04
    • 1970-01-01
    • 2019-06-10
    • 2014-01-15
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多