PHP 根据 HTML 表单输入文件 ID 重命名图像


PHP rename image based on HTML form input file ID

我想知道是否可以根据表单输入文件 ID 重命名图像。

<form action="upload_file.php" enctype="multipart/form-data" method="post">
    <input id="picture_01"  type="file">
    <input id="picture_02"  type="file">
    <input id="picture_03"  type="file">
    <input id="picture_04"  type="file">
<input name="submit" type="submit" value="Submit">
</form>

我希望如果图像是从输入 4 上传的,它将被重命名为"picture_04",如果它来自输入表单 2,它将重命名为"picture_02"。不是按顺序,而是根据输入表单框。

尽管进行了各种试验和错误,但我还是无法做到这一点。

我会为每个输入使用单独的表单。这样,您可以使用隐藏的输入,例如:

<form action="upload_file.php" enctype="multipart/form-data" method="post">
   <input type='hidden' name='picture_03_file' value="picture_03" />
   <input type='file'   name='picture_03_name' />
</form>
<form action="upload_file.php" enctype="multipart/form-data" method="post">
   <input type='hidden' name='picture_04_file' />
   <input type='file'   name='picture_04_name' value="picture_04" />
</form>

这样你的PHP代码就会看起来像:

$imgName = $_POST['picture_04_name'];
// Do file upload here

您需要命名您的输入:

<input id="picture_01" name="picture_01" type="file">

等。

然后在 PHP 中,您可以使用 $_FILES 数组检索图像,例如 $_FILES['picture_01'] 或简单地循环遍历$_FILES

foreach( $_FILES as $input_name=>$file)
{
  // $input_name is the name used as the form input name
  // $file is an array with the following keys: name, type, tmp_name, error, size.
}

当然,手册总是一本好读 http://www.php.net/manual/en/features.file-upload.post-method.php