2016-10-19 25 views
-1

我試圖隱藏圖像框,直到文件被設置在我的文件上傳代碼中。現在它顯示$preview圖像框,無論是否已設置文件。if(isset)隱藏一個元素直到它被設置爲

我在做什麼錯?

<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> 
+2

好,'$ preview_file'顯然會永遠是空的,因爲你明確地將一個字符串分配給它只有兩行。 – arkascha

+2

我認爲你對什麼運行在哪裏感到困惑。這是不可能直接使用PHP的。 PHP在服務器上運行,而不是在客戶端上運行。當你看到這個頁面時,PHP已經完成了(給予或帶走)。動態頁面間交互需要JS完成(需要時使用AJAX)。 –

+0

它會這樣做,你正在設置'$ preview_file',然後它下面的2行檢查是否爲空,它不會是。 – Blinkydamo

回答

0

不需要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); 
}); 
+0

但他想用php –

+1

謝謝!這很好。 – Paul

+0

@downvoter爲什麼你投下了票?甚至,答案似乎也很有幫助。請在投票前進行思考。 –

1

如果你想用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>