如何用javascript FileReader检测文件扩展名 [英] How to detect file extension with javascript FileReader
本文介绍了如何用javascript FileReader检测文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用javascript的FileReader和我的自定义函数来读取JPG-JPEG图像,
我的问题是如何通过下面的代码检测文件扩展名,如果文件是不是JPG-JPEG:
I'm using javascript's FileReader and my customized function for reading an JPG-JPEG image, My problem is that how it's possible to detect the file extension through my code below and give error to user if the file is not 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]);
}
}
推荐答案
你可以试试这个,
我改变你的代码如下:
You can try this, I changed your code as follows:
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
}
}
}
这篇关于如何用javascript FileReader检测文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文