如何使用javascript FileReader检测文件扩展名

我正在使用javascript的FileReader和我的自定义函数来读取JPG-JPEG图像,我的问题是如何通过下面的代码检测文件扩展名,如果文件不是JPG-JPEG则给用户错误:

function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { alert('image has read completely!'); } reader.readAsDataURL(input.files[0]); } } 

您可以试试这个,我更改了您的代码如下:

 var fileTypes = ['jpg', 'jpeg', 'png', 'what', 'ever', 'you', 'want']; //acceptable file types function readURL(input) { if (input.files && input.files[0]) { var extension = input.files[0].name.split('.').pop().toLowerCase(), //file extension from input file isSuccess = fileTypes.indexOf(extension) > -1; //is extension in acceptable types if (isSuccess) { //yes var reader = new FileReader(); reader.onload = function (e) { alert('image has read completely!'); } reader.readAsDataURL(input.files[0]); } else { //no //warning } } } 

没有直接接口来读取文件扩展名。 您至少有两个选择:

  • 使用正则表达式从文件名中提取扩展名
  • 使用文件的内容类型作为filter

对于扩展方法,它类似于:

 var extension = fileName.match(/\.[0-9a-z]+$/i);