js或jquery file.type.match仅适用于jpg和png [英] Js or jquery file.type.match for jpg and png only

查看:174
本文介绍了js或jquery file.type.match仅适用于jpg和png的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用file.type.match

How can I limit the mimetype for only png and jpg using 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");
}


推荐答案

从你的问题听起来像你不想做类似的事情:

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");
}

看到这个小提琴进行测试。

这篇关于js或jquery file.type.match仅适用于jpg和png的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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