在javascript上传之前,只有特定文件显示(例如PDF)

时间:2015-12-11 19:47:09

标签: javascript html5

我有一个场景,我只允许上传特定的文件类型,例如PDF。 我不想在表单提交时验证类型。在选择文件之前,我需要验证类型是否正常。请注意,HTML5不支持accept属性。

我有两个选择。

  1. 只有可接受的文件类型可供选择。
  2. 如果可能,请在选择文件后触发Javascript功能。与onclick相反。
  3. 这就是我尝试在提交时验证的方式:

    <form name="fileupload" onsubmit="return file_upload();">
        <table align="center" bgcolor="#8080FF" height="100">
            <tr>
                <th> Fileupload:</th>
                <td> <input type="file" name="word" id="word" > </td>
            </tr>
            <tr>
                <td> <input type="submit" /> </td>
            </tr>
        </table>
    </form>
    <script type="text/javascript">
    
        function file_upload()
        {
            var imgpath = document.getElementById('word').value;
            if (imgpath == "") {
                alert("upload your word file");
                document.file.word.focus();
                return false;
            }
            else {
                // code to get File Extension..
                var arr1 = new Array;
                arr1 = imgpath.split("\\");
                var len = arr1.length;
                var img1 = arr1[len - 1];
                var filext = img1.substring(img1.lastIndexOf(".") + 1);
                // Checking Extension
                if (filext == "doc" || filext == "docx") {
                    alert("File has been upload correctly")
                    return true;
                }
                else {
                    alert("Invalid File Format Selected");
                    document.form.word.focus();
                    return false;
                }
            }
        }
    </script>
    

0 个答案:

没有答案
相关问题