简体   繁体   English

使用javascript上传文件页面验证

[英]upload file page validation using javascript

This is the file upload page : 这是文件上传页面:

<input type="file" id="fileUpload" />
<input type="submit" value="Upload File" style="margin: 40px 0 0 160px"/>
<div id="fileSelect" style="color:Red;display:none">No file selected for uploading.</div>
<div id="fileFormat" style="color:Red;display:none">Invalid File Format. Only .xlsx, .xls, and .xlt file format allowed.</div>
</form>

This is the JavaScript validation: 这是JavaScript验证:

<script>
var _validFileExtensions = [".xlsx", ".xls", ".xlt"]; 
function Validate(oForm) {
if( document.getElementById("fileUpload").files.length == 0 ){
     document.getElementById("fileSelect").style.display=""; 
    return false;
}

    var arrInputs = oForm.getElementsByTagName("input");
    for (var i = 0; i < arrInputs.length; i++) {
        var oInput = arrInputs[i];
        if (oInput.type == "file") {
            var sFileName = oInput.value;
            if (sFileName.length > 0) {
                var blnValid = false;
                for (var j = 0; j < _validFileExtensions.length; j++) {
                    var sCurExtension = _validFileExtensions[j];
                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                        blnValid = true;
                        break;
                    }
                }

                if (!blnValid) {
                    document.getElementById("fileFormat").style.display="";
                    return false;
                }
            }
        }
    }

    return true;
}  

</script>

Now the issue happening is 现在发生的问题是

when I click on Upload button I get the following message: 当我单击上按钮时,出现以下消息:

No file selected for uploading. 未选择要上传的文件。

Now I don't refresh the page and browse for the invalid file and click Upload . 现在,我不再刷新页面并浏览无效的文件,然后点击上传 It now shows: 现在显示:

No file selected for uploading. 未选择要上传的文件。

Invalid File Format. 无效的文件格式。 Only .xlsx, .xls, and .xlt file format allowed. 仅允许使用.xlsx,.xls和.xlt文件格式。

I want the earlier message to not be displayed. 我希望不显示以前的消息。 It should only display: 它应该只显示:

Invalid File Format. 无效的文件格式。 Only .xlsx, .xls, and .xlt file format allowed. 仅允许使用.xlsx,.xls和.xlt文件格式。

But the following message is also displayed 但是也会显示以下消息

No file selected for uploading 未选择要上传的文件

You are never resetting the display value to hidden, so no matter what once it is changed to a blank string, it won't change back... Try this: 您永远不会将display值重置为隐藏,因此无论将其更改为空白字符串如何,它都不会更改回...请尝试以下操作:

if( document.getElementById("fileUpload").files.length == 0 ){
     document.getElementById("fileSelect").style.display=""; 
    return false;
}
else {
     document.getElementById("fileSelect").style.display="none"; 
}        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM