Ant*_*ony 133 javascript jquery file-upload file-type
我想让jQuery将文件上传字段限制为仅jpg/jpeg,png和gif.我正在进行后端检查PHP
.我JavaScript
已经通过一个函数运行我的提交按钮所以我真的只需要知道在提交或提醒之前如何检查文件类型.
Pao*_*ino 274
您可以获取文件字段的值与任何其他字段相同.但是,你不能改变它.
因此,为了表面检查文件是否具有正确的扩展名,您可以执行以下操作:
var ext = $('#my_file_field').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
alert('invalid extension!');
}
Run Code Online (Sandbox Code Playgroud)
小智 39
没有必要的插件才能完成这项任务.从其他几个脚本拼凑出来:
$('INPUT[type="file"]').change(function () {
var ext = this.value.match(/\.(.+)$/)[1];
switch (ext) {
case 'jpg':
case 'jpeg':
case 'png':
case 'gif':
$('#uploadButton').attr('disabled', false);
break;
default:
alert('This is not an allowed file type.');
this.value = '';
}
});
Run Code Online (Sandbox Code Playgroud)
这里的技巧是将上传按钮设置为禁用,除非并且直到选择了有效的文件类型.
Jul*_*urg 27
您可以使用jQuery的验证插件:http: //docs.jquery.com/Plugins/Validation
碰巧有一个accept()规则完全符合你的需要:http: //docs.jquery.com/Plugins/Validation/Methods/accept#extension
请注意,控制文件扩展名不是防弹,因为它与文件的mimetype无关.所以你可以有一个.png,它是一个word文档,而.doc是一个完全有效的png图像.所以不要忘记在服务器端进行更多控制;)
dhr*_*tel 24
对于前端,如果您使用文件字段,则放置' accept '属性非常方便.
例:
<input id="file" type="file" name="file" size="30"
accept="image/jpg,image/png,image/jpeg,image/gif"
/>
Run Code Online (Sandbox Code Playgroud)
几个重要的注意事项:
Leo*_*Leo 19
不想检查MIME而不是用户所说的任何扩展?如果是这样,那么它不到一行:
<input type="file" id="userfile" accept="image/*|video/*" required />
Run Code Online (Sandbox Code Playgroud)
对于我的情况,我使用了以下代码:
if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(fileName)) {
alert('You must select an image file only');
}
Run Code Online (Sandbox Code Playgroud)