如何让 jQuery 限制上传的文件类型? [英] How to have jQuery restrict file types on upload?

查看:36
本文介绍了如何让 jQuery 限制上传的文件类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让 jQuery 将文件上传字段限制为仅 jpg/jpeg、png 和 gif.我已经在用 PHP 做后端检查了.我已经通过 JavaScript 函数运行我的提交按钮,所以我真的只需要知道如何在提交或警报之前检查文件类型.

I would like to have jQuery limit a file upload field to only jpg/jpeg, png, and gif. I am doing backend checking with PHP already. I am running my submit button through a JavaScript function already so I really just need to know how to check for the file types before submit or alert.

推荐答案

您可以像获取任何其他字段一样获取文件字段的值.但是,您无法更改它.

You can get the value of a file field just the same as any other field. You can't alter it, however.

因此要表面检查文件是否具有正确的扩展名,您可以执行以下操作:

So to superficially check if a file has the right extension, you could do something like this:

var ext = $('#my_file_field').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
    alert('invalid extension!');
}

这篇关于如何让 jQuery 限制上传的文件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆