文件类型有限的 HTML 文件输入字段? [英] HTML file input field with limited file types?

查看:20
本文介绍了文件类型有限的 HTML 文件输入字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 HTML 文件输入字段,有什么方法可以限制它只允许上传图片?我确信使用 Flash 或 Java 可以做到这一点,但我暂时尽量远离它们.

If I have an HTML file input field, is there any way that I can limit it to only allow image uploads? I'm sure this would be possible with Flash or Java, but I'm trying to stay away from them for the time being.

我在网上找到了接受"属性,但它似乎没有为我做任何事情(或者我用错了.).感谢任何帮助或示例.

I found the "accept" attribute online, but it doesn't seem to be doing anything for me (or I'm using it wrong.). Any help or examples is appreciated.

推荐答案

最好的方法是在后端处理.根据您想要允许的类型类型和后端技术,您会找到各种方法来执行此操作.

The best way is to handle that in the backend. Depending on the type of types you want to allow and the backend technology you will find various ways of doing this.

您也可以在 javascript 中执行此操作,但您会受到更多限制,并且可能会导致跨浏览器出现问题:

You can also do this in javascript but you'll be more limited and it might lead to issues crossbrowser:

if((document.form1.upload.value.lastIndexOf(".jpg")==-1) {
   alert("Please upload only .jpg extention file");
   return false;
}

(通过)

如果您使用 jquery,请查看以下问题:如何有 jQuery 在上传时限制文件类型吗?

If you use jquery, checkout this question: How to have jQuery restrict file types on upload?

您也可以使用 JQuery Validation 插件.

You can also use the JQuery Validation plugin.

$("#myform").validate({
  rules: {
    field: {
      required: true,
      accept: "xls|csv"
    }
  }
});

(通过)

这篇关于文件类型有限的 HTML 文件输入字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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