我正在尝试创建一个表单,允许在提交上传之前重命名表单中的选定文件。
我创建了一个名为"new_fileName"的"text"字段的表单。除了文件选择器。
在upload.php端,我将变量更改为$newname,并尝试了几种方法来使用该变量更改上传文件的名称。包括使用它来替换$filename变量的['name']部分。但到目前为止,还没有任何成功。
形式<!DOCTYPE html>
<html>
<head>
<title> Rename and Upload Form </title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" >
<input type="file" name="file" id="file" />
<br><br>
<input type="text" name="new_fileName" placeholder="Rename File"/>
<br><br>
<input type="submit" value="Rename and Upload" />
</form>
</body>
</html>
upload.php
<?php
$newname = $_POST['new_fileName'];
$filename = $_FILES['file']['name'];
$location = "upload/".$filename;
if( move_uploaded_file($_FILES['file']['tmp_name'], $location)){
echo 'File uploaded successfully';
}else{
echo 'Error uploading file';
}
?>
在对'upload.php'页面进行了一些修改后,在提交上传表单之前更改了文件的名称。
此代码还将文件类型扩展名添加到新文件名。
(新)upload.php
<?php
$filename = $_POST['new_fileName'];
$name = $_FILES["file"]["name"];
$ext = end((explode(".", $name)));
if($_SERVER["REQUEST_METHOD"] == 'POST') {
if ($_FILES['file']['error'] > 0) { echo 'Error: ' . $_FILES['file']
['error']; }
if (file_exists('upload/' . $_FILES['file']['name'])) { unlink
('upload/' . $_FILES['file']['name']); }
move_uploaded_file($_FILES['file']['tmp_name'], 'upload/' . $_POST =
$filename . "." . $ext);
echo 'File uploaded successfully' ; }
else { echo 'Error uploading file'; }
?>