【问题标题】:Check if File Exists / Append Number with Name检查文件是否存在/使用名称附加编号
【发布时间】:2015-11-03 08:27:42
【问题描述】:

我创建了一个上传文件表单。它工作正常,但我无法检查文件是否存在。如果是,那么它应该自动重命名。

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";
    }
?>

【问题讨论】:

标签: php


【解决方案1】:

检查这个,我使用了 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";
}
?>

【讨论】:

  • 另外,假设文件名包含空格,我可以用 - 或 _ 替换空格
【解决方案2】:

您必须检查是否设置了 $_FILES["file1"] 变量。

例如:

$file = (isset($_FILES["file1"]) ? $_FILES["file1"] : 0);

if(!file) { die("ERROR: Please browse for a file before clicking the upload button."); }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-09
    • 2023-02-17
    • 1970-01-01
    • 2015-11-19
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多