我正在使用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
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句