php - 如何在 php 中使用上传和自定义文件名创建上传表单?
问题描述
您好我正在尝试在 php 中创建一个上传表单。包含、上传输入、文本输入(上传文件的名称)和提交按钮。但是我不太了解,php,
所以我不知道如何实际链接我输入的内容在<input type="text"/>
上传时成为文件的名称。如果有人可以帮忙?谢谢。
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>Tu peux uploader ici ta video.</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<p>Upload your file</p>
<input type="file" name="uploaded_file"></input><br />
<input type="text" name="file-name"></input><br /> <!-- [ASK]: How to make this the file name of the uploaded file -->
<input type="submit" value="Upload"></input>
</form>
</body>
</html>
<?PHP
if(!empty($_FILES['uploaded_file']))
{
$path = "uploads/";
$path = $path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
?>
解决方案
move_uploaded_file ( string $filename , string $destination ) 采用 filename ,它是上传文件的文件名,destination 是移动文件的目标。注意目标目录必须存在;move_uploaded_file() 不会自动创建它。所以现在让我们来取名字......
- $_FILES['uploaded_file']['tmp_name'] 为您提供上传文件存储在服务器上的文件的临时文件名,例如。C:\Users\USER\AppData\Local\Temp\phpD3C.tmp 而
- $_FILES['uploaded_file']['name'] 为您提供提取扩展名所需的实际名称,例如。我的文件.jpg
- 要链接您在 上键入的内容,首先通过 $_POST["file-name"] 获取它,然后与扩展名连接。使用 pathinfo 检索原始扩展名。
将您的代码更改为...
<!DOCTYPE html>
<html>
<head>
<title>Tu peux uploader ici ta video.</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<p>Upload your file</p>
<input type="file" name="uploaded_file"></input><br />
<input type="text" name="file-name"></input><br /> <!-- [ASK]: How to make this the file name of the uploaded file -->
<input type="submit" value="Upload"></input>
</form>
</body>
</html>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(!empty($_FILES['uploaded_file']))
{
$file_parts = pathinfo(basename( $_FILES['uploaded_file']['name'])); //access the actual name instead of tmp_name
//just pick the extension of the file_parts and concatenate it to your path
$path = 'images/';
$path = $path . $_POST["file-name"] . "." . $file_parts['extension'] ;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo "The file ". basename($path) ." has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
这应该会为您提供所需的名称。因此,如果您上传文件 dog.php 并且在文本字段中有牛,则结果名称应该是 cow.php。