如何使用Javascript/jquery验证文件上载字段

Cli*_*ote 18 javascript jquery

如何验证用户是否选择了要上传的文件?

编辑:碰撞

Sie*_*tse 27

检查它的value属性:

在jQuery中(因为你的标签提到它):

$('#fileInput').val()
Run Code Online (Sandbox Code Playgroud)

或者在vanilla JavaScript中:

document.getElementById('myFileInput').value
Run Code Online (Sandbox Code Playgroud)


Rav*_*ngh 20

我的功能将检查用户是否选择了该文件,您还可以检查是否要允许该文件扩展名.

试试这个:

<input type="file" name="fileUpload" onchange="validate_fileupload(this.value);">

function validate_fileupload(fileName)
{
    var allowed_extensions = new Array("jpg","png","gif");
    var file_extension = fileName.split('.').pop().toLowerCase(); // split function will split the filename by dot(.), and pop function will pop the last element from the array which will give you the extension as well. If there will be no extension then it will return the filename.

    for(var i = 0; i <= allowed_extensions.length; i++)
    {
        if(allowed_extensions[i]==file_extension)
        {
            return true; // valid file extension
        }
    }

    return false;
}

  • for循环应该是i <allowed_extensions.length; NOT <=因为这将在上面的例子中进行循环的四次迭代,因此将未定义的文件名传递给函数将返回TRUE. (2认同)