javascript js 或 jquery file.type.match 仅适用于 jpg 和 png

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14345755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:23:55  来源:igfitidea点击:

Js or jquery file.type.match for jpg and png only

javascriptjquerymime-types

提问by vzhen

How can I limit the mimetype for only png and jpg using file.type.match

如何使用 file.type.match 限制仅 png 和 jpg 的 mimetype

below is my code

下面是我的代码

var fileInput = document.getElementById("myfileinput").files[0];

if (fileInput.type.match('image/jpeg'))  
      //I not thinking to use if(xx || xx)
      //prefer using var mimeType = jpg,png  many tries but not work
{
alert("Right");
}else{
alert("wrong");
}

回答by Kyle Weller

from your question it sounds like you don't want to do something like:

从你的问题听起来你不想做这样的事情:

if (fileInput.type.match('image/jpeg') || fileInput.type.match('image/png'))  
  //I not thinking to use if(xx || xx)
  //prefer using var mimeType = jpg,png  many tries but not work
{
  alert("Right");
}else{
  alert("wrong");
}

You can make an array of acceptable extensions and loop through them like:

您可以制作一系列可接受的扩展并循环遍历它们,例如:

var fileInput = document.getElementById("myfileinput").files[0];
var allowed = ["jpeg", "png"];
var found = false;

allowed.forEach(function(extension) {
  if (fileInput.type.match('image/'+extension)) {
    found = true;
  }
})

if(found) {
  alert("Right");
}
else{
  alert("wrong");
}

See this fiddlefor a test.

请参阅此小提琴进行测试。

回答by lrkrol

It can also be done in one line with |as the OR operator:

也可以使用|OR 运算符在一行中完成:

if (fileInput.type.match('image/jpeg|image/png')) {...}

if (fileInput.type.match('image/jpeg|image/png')) {...}