这是我的文件上传器:
<form action="done.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" value="upload">Upload</button>
</form>
如果我没有选择任何文件,我点击&#34;提交&#34;,我将被重定向到done.php。
如果没有选择文件,我点击提交,我想留在我的网站上并收到错误消息&#34;没有选择文件&#34;。
done.php:
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
$target_file = 'files/'.basename($_FILES["file"]["name"]);
$filename = $target_file;
if (file_exists($target_file)) {
echo "file already existes";
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
}
}
我现在更新了我的代码,就像Florian建议的那样:
done.php:
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
$target_file = 'files/'.basename($_FILES["file"]["name"]);
$filename = $target_file;
if (file_exists($target_file)) {
echo "file already existes";
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
}
}
else {
echo 'No file selected. <a href="upload.html">Back to upload form</a>';
}
现在发生的是,当我没有选择任何文件时,我收到错误消息:&#34;文件已存在&#34;。我不明白为什么。
答案 0 :(得分:2)
将您的done.php扩展如下:
if(!file_exists($_FILES['file']['tmp_name']) || !is_uploaded_file($_FILES['file']['tmp_name'])) {
$file = $_FILES['file'];
$target_file = 'files/'.basename($_FILES["file"]["name"]);
$filename = $target_file;
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
} else {
echo 'No file selected. <a href="./upload.html">Back to upload form</a>';
// maybe you want to include the upload form here or do something else
}
答案 1 :(得分:1)
取决于您的&#34;查看代码&#34;它可能是那样的
<form action="done.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="hidden" name="todo" value="fileupload"?>
<button type="submit" value="upload">Upload</button>
</form>
<?php if($_POST && !$_FILES):?>
<h3>"No file selected".</h3>
<?php endif;?>
答案 2 :(得分:1)
<html>
<head>
<style>
li
{
display: inline-block;
}
</style>
<script>
function formValidation()
{
if(document.getElementById("fileName").value==""||document.getElementById("fileName").value==null)
{
alert("no file selected");
return false;
}
else
return true;
}
</script>
</head>
<body>
<form action="done.php" method="post" enctype="multipart/form-data" onSubmit="return formValidation()">
<input id="fileName" type="file" name="file">
<button type="submit" value="upload">Upload</button>
</form>
</body>
</html>
答案 3 :(得分:1)
<html>
<body>
<script>
function unlock(){
document.getElementById('buttonSubmit').removeAttribute("disabled");
}
</script>
<form action="done.php" method="post" enctype="multipart/form-data">
<input type="file" onchange="unlock();" name="file">
<button type="submit" id="buttonSubmit" value="upload" disabled>Upload</button>
</form>
</body>
</html>
答案 4 :(得分:0)
您可以使用
进行检查if(strlen($_FILES[$mcFile]['name'])==0){
echo "Error No file selected ";
}
OR
if ($_FILES["file"]["error"] > 0){
echo "Error No file selected ";
}
这两种方法都是在服务器端检查文件验证的方法