我的页面中有一个文件上传。我定义了一个名为“filetype”的属性。
<input filetype=".jpg|.jpeg|.png" id="attachments" type="file">
我希望当我从文件上传中选择一个文件时,使用 JavaScript 检查文件类型:
function onSelect(e) {
if (!e.files[0].extension.match('/' + $("input[type='file']").attr('filetype') + '/i')) {
alert('file type is wrong');
e.preventDefault();
}
}
现在,当我选择 .jpg 格式的文件时,e.files[0].extension 将是
.jpg
和 '/' + $("input[type='file']").attr('filetype') + '/i' 是
/.jpg|.jpeg|.png/i
但是 e.files[0].extension.match('/' + $("input[type='file']").attr('filetype') + '/i') 返回
null
然后发出火灾警报。 为什么?我如何解决这个问题? 谢谢。
最佳答案
您无法使用连接构建文字正则表达式,您需要使用 RegExp 构造函数。
我建议您执行以下操作:
<input data-filetype="jpg|jpeg|png" id="attachments" type="file">
然后:
function onSelect(e) {
// "this" is the file input
// if you attach the function to an event
// like `$('input:file').change(onSelect)`
var filetypes = $(this).data('filetype');
var re = RegExp('\\.('+ filetypes +')$','i');
if (!re.test(e.files[0].extension)) {
alert('file type is wrong');
e.preventDefault();
}
}
关于文件上传中的javascript正则表达式和文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23486570/