if (isset) 隐藏一个元素直到它被设置

if (isset) to hide an element until it is set

我试图隐藏一个图像框,直到在我的文件上传代码中设置了一个文件。现在无论是否设置了文件,它都会显示 $preview 图像框。

我做错了什么?

<form action="" method="POST" enctype="multipart/form-data">
    Change your profile picture <br><input type="file" name="file" class="inputbarfile" onchange="readURL(this);">
    <?php
    $preview_file = '<input type="file" name="file" class="inputbarfile" onchange="readURL(this);">';
    $preview =  '<img width="300px" height="200px" id="file" src="#" alt="your image">';
    if (empty($preview_file)) {
        '';
    } else {
        echo $preview;
    } ?>
    <input type="submit" name="create" value="Upload">
</form>

无需 PHP 条件,您可以使用 jquery.

实现此目的

HTML

<form action="" method="POST" enctype="multipart/form-data">
    Change your profile picture <br>
    <input type="file" name="file" class="inputbarfile">
    <img width="300px" height="200px" id="file" src="#" alt="your image" style="display: none;">
    <input type="submit" name="create" value="Upload">
</form>

img标签中设置style="display:none"和文件输入的onchange事件使图片标签如下所示。

从文件上传元素中删除 onchange 并改为使用 jquery change 事件,如下所示。您的 readURL 函数将保持原样。

$(".inputbarfile").change(function(){
  $("#file").show();
  readURL(this);
});

如果你只想用 PHP 来做,你的代码应该如下所示(除了 $_POST htmlstrips 的安全性,转义):

<?php if (isset($_POST['file'])):?>
    <?php $file = $_POST['file']; //#SECURE You should escape here ?>
    File:  <?php echo $file; ?>
    Image: <img width="300px" height="200px" id="file" src="path/to/image/<?php echo $file ?>" alt="your image" />
<?php endif; ?>

<form action="#" method="POST" enctype="multipart/form-data">
    Change your profile picture <br>
    <input type="file" name="file" class="inputbarfile" onchange="readURL(this);" />
    <input type="submit" name="create" value="Upload" />
</form>