输入文件多重验证Javacript

发布于 2025-02-03 22:47:29 字数 63 浏览 4 评论 0原文

可以在多个输入文件中验证一个文件之一是类型word(.doc,.docx)和类型pdf(.pdf)的另一个文件?

It is possible to validate within a multiple Input file that one of the files is of type word (.doc, .docx) and another of type PDF (.pdf)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怀中猫帐中妖 2025-02-10 22:47:29

我有一个创建的a working codepen ,该向您显示一个javascript代码文件上传输入,并检查其文件扩展名是在PDF,DOC还是DOCX中。

尽管正如其他人在评论中提到的那样,在客户端检查文件格式是不安全的,您应该在服务器端进行仔细检查。

下面的摘要

function testFiles(){
        var fileInput = document.getElementById('upload');   
        // iterate over files
        for (let i = 0; i < fileInput.files.length; i++) {
            var filename = fileInput.files[i].name
            // get file extension
            var file_extension = filename.split('.').pop()
            if(file_extension == "pdf" 
               || file_extension == "doc"
               || file_extension == "docx"){
              alert(filename + ' is a .pdf, .doc or .docx file')
            }                 
            else alert(filename + ' is not an authorized file')
        }
}
 <input id="upload" type="file" onchange="testFiles()" multiple>

I have a created a working codepen that shows you a javascript code which iterates over the files uploaded with the file upload input, and checks if their file extension is in pdf, doc or docx.

Though as others have mentioned in comments, checking file format in client-side is unsafe and you should double check on the server side.

Snippet below

function testFiles(){
        var fileInput = document.getElementById('upload');   
        // iterate over files
        for (let i = 0; i < fileInput.files.length; i++) {
            var filename = fileInput.files[i].name
            // get file extension
            var file_extension = filename.split('.').pop()
            if(file_extension == "pdf" 
               || file_extension == "doc"
               || file_extension == "docx"){
              alert(filename + ' is a .pdf, .doc or .docx file')
            }                 
            else alert(filename + ' is not an authorized file')
        }
}
 <input id="upload" type="file" onchange="testFiles()" multiple>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文