我创建了一个上传文件表单。它工作正常,但我无法检查文件是否存在。如果是,则应自动重命名。
HTML代码: -
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress><br><br>
Below is the direct link to file :-
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
PHP代码: -
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "upload/$fileName")){
echo "$fileName uploaded";
} else {
echo "move_uploaded_file function failed";
}
?>
答案 0 :(得分:0)
检查一下,我使用了file_exists()函数
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
$fileReadyForUpload = "upload/" . $fileName;
if (file_exists($fileReadyForUpload)) {
$fileName = time() . "_" . $fileName;
} else {
$fileName = $fileName;
}
if (move_uploaded_file($fileTmpLoc, "upload/$fileName")) {
echo "$fileName uploaded";
} else {
echo "move_uploaded_file function failed";
}
?>
答案 1 :(得分:0)
您必须检查是否设置了$ _FILES [“file1”]变量。
例如:
$file = (isset($_FILES["file1"]) ? $_FILES["file1"] : 0);
if(!file) { die("ERROR: Please browse for a file before clicking the upload button."); }