使用Javascript进行文件类型验证

时间:2011-11-22 17:30:08

标签: javascript

我对JavaScript验证有疑问。每当我的脚本运行时,我都会验证<input type="file">,它会验证,但也会调用操作页面。我想停止操作页面,直到验证完成。这是我的代码,任何帮助都会很棒。此致

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Image Uploading</title>
    </head>


    <body>
        <form name="xx" action="server.php" method="post" enctype="multipart/form-data" onsubmit="Checkfiles(this)">
            <input type="file" name="file_uploading" id="filename">
            <input type="submit" value="Submit" name="uploadfile">
        </form>

        <form name="view" method="post">
            <a href="view_server.php">View your uploaded Images</a>
        </form>
    </body>
</html>

<script type="text/javascript">
    function Checkfiles()
    {
        var fup = document.getElementById('filename');
        var fileName = fup.value;
        var ext = fileName.substring(fileName.lastIndexOf('.') + 1);

    if(ext =="GIF" || ext=="gif")
    {
        return true;
    }
    else
    {
        alert("Upload Gif Images only");
        return false;
    }
    }
</script>

9 个答案:

答案 0 :(得分:15)

var fname = "the file name here.ext"; 
var re = /(\.jpg|\.jpeg|\.bmp|\.gif|\.png)$/i;
if(!re.exec(fname))
{
alert("File extension not supported!");
}

答案 1 :(得分:2)

提交处理程序的返回值会影响提交。

onsubmit="return Checkfiles();"

这基本上是在说:

form.onsubmit = function () { return Checkfiles(); };

答案 2 :(得分:2)

您可以使用File Api来测试magic number。也许请查看this answer以了解有关验证的其他想法。比文件扩展名检查更可靠。

答案 3 :(得分:2)

通过javascript

进行文件扩展名验证
function ValidateExtension() {
        var allowedFiles = [".doc", ".docx", ".pdf"];
        var fileUpload = document.getElementById("fileUpload");
        var lblError = document.getElementById("lblError");
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
        if (!regex.test(fileUpload.value.toLowerCase())) {
            lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
            return false;
        }
        lblError.innerHTML = "";
        return true;
    }

提交按钮的onclick事件调用此javascript函数。

在ID = lblError的帮助下,在html部分打印错误消息。

答案 4 :(得分:1)

您需要返回 CheckFiles()

答案 5 :(得分:1)

通过Excel工作表(.csv)上传批量数据

&#13;
&#13;
$("form").submit(function(){
 var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(csv)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Only csv file can be uploaded');
return false;
} 

});
&#13;
&#13;
&#13;

答案 6 :(得分:0)

select eeid, code1, 'code1' as which, sum(value1)
from t
where code1 is not null
group by eeid, code1
union all
select eeid, code2, 'code2' as which, sum(value2)
from t
where code2 is not null
group by eeid, code2;

答案 7 :(得分:0)

通常,您可以使用javascript some()方法。

function isImage(icon) {
  const ext = ['.jpg', '.jpeg', '.bmp', '.gif', '.png', '.svg'];
  return ext.some(el => icon.endsWith(el));
}

let fname = "the file name here.ext";
if (!isImage(fname)) {
  alert("File extension not supported!");
}

答案 8 :(得分:0)

fileValidation() 函数包含完整的文件类型验证代码。此 JavaScript 函数需要调用文件扩展名验证。

HTML

<!-- File input field -->
<input type="file" id="file" onchange="return fileValidation()"/>

<!-- Image preview -->
<div id="imagePreview"></div>

JavaScript

function fileValidation(){
    var fileInput = document.getElementById('file');
    var filePath = fileInput.value;
    var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
    if(!allowedExtensions.exec(filePath)){
        alert('Please upload file having extensions .jpeg/.jpg/.png/.gif only.');
        fileInput.value = '';
        return false;
    }else{
        //Image preview
        if (fileInput.files && fileInput.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('imagePreview').innerHTML = '<img src="'+e.target.result+'"/>';
            };
            reader.readAsDataURL(fileInput.files[0]);
        }
    }
}

fileValidation()