Bay*_*aya 18 javascript jquery html5
我正在使用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]);
}
}
Run Code Online (Sandbox Code Playgroud)
Eng*_*tün 38
您可以试试这个,我更改了您的代码如下:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
没有直接的接口来读取文件扩展名。你至少有2个选择:
对于扩展方法,它会是这样的:
var extension = fileName.match(/\.[0-9a-z]+$/i);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24381 次 |
| 最近记录: |