2011-03-21 17 views
0

嗨,我使用PHP和MySQL。當沒有選擇文件上傳文件字段使用javascript時的警報彈出

我有一個表格爲用戶添加記錄。 用戶應該提示何時他不會選擇要上傳的文件,以便保存沒有圖像的數據。

我們能做到這一點使用JavaScript ..

如果任何人知道這將不勝感激..提前

感謝

+0

「用戶應該提示他什麼時候不會選擇要上傳的文件,以便在沒有圖像的情況下保存數據。」即你有一些圖像清單,供用戶選擇,如果(他)沒有上傳任何圖像,,我是對的... – Naresh 2011-03-21 06:01:29

回答

2

您可以使用javascript驗證文件輸入。

下面是一個例子:

function checkFile(yourForm){ 

    var fileVal = yourForm.elements['fileField'].value; 

    //RegEx for valid file name and extensions. 
    var pathExpression = "[?:[a-zA-Z0-9-_\.]+(?:.png|.jpeg|.gif)"; 


    if(fileVal != ""){ 
     if(!fileVal.toString().match(pathExpression) && confirm("The file is not a valid image. Do you want to continue?")){ 
      yourForm.submit(); 
     } else { 
      return; 
     } 
    } else { 
     if(confirm("Do you want to continue without adding image?")) { 
      yourForm.submit(); 
     } else { 
      return; 
     } 
    } 
} 

在HTML

<form name="yourForm" method="post" enctype="multipart/form-data""> 
    <input type="file" name="fileField" /> 
    <input type="button" value="submit" onClick="checkFile(this.form)" /> 
</form> 

注pathExperssion可定製。另一件事是檢查擴展是不是太可靠,因爲任何人都可以注入一個文件名作爲擴展名。其他信息請點擊here

1

只是檢查,看看是否該字段爲空,然後問他們如果這真的是他們想要的...

if(document.forms["uploadForm"].elements["imageField"].value == "" 
    && confirm("You have not added an image, are you sure you want to continue?") 
) 
     upload(); 
    else 
     doNothing(); 
相關問題