尊敬的先生,此代码工作fine.But我需要JavaScript验证与文件类型和文件大小.When每当我上传一个文件的同时,它检查文件大小和文件扩展名,以便它产生所需的result.Please帮助我更正代码我将感谢you.looking的积极响应
$('#image-file').on('change', function() {
var numb = $(this)[0].files[0].size/1024/1024;
numb = numb.toFixed(2);
if(numb > 2){
alert('to big, maximum is 2MB. You file size is: ' + numb +' MB');
} else {
alert('it okey, your file has ' + numb + 'MB')
}
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="file" id="image-file">
发布于 2020-07-14 16:04:06
使用lastIndexOf获取最后一个\作为索引,使用substr获取从最后一个索引\开始的剩余字符串
// find elements
$('#image-file').on('change', function() {
var uploadedFile = $(this)[0].files[0];
const name = uploadedFile.name;
console.log(name);
const lastDot = uploadedFile.name.lastIndexOf('.');
const fileName = name.substring(0, lastDot);
const ext = name.substring(lastDot + 1).toLowerCase();
// you can add extension here which allowed to upload
if(['png','gif','jpeg','jpg'].includes(ext)){
alert('file is image');
}else{
alert('file is not an image');
return false;
}
var numb = uploadedFile.size/1024/1024;
numb = numb.toFixed(2);
if(numb > 2){
alert('to big, maximum is 2MB. You file size is: ' + numb +' MB');
return false;
} else {
alert('it okey, your file has ' + numb + 'MB')
}
})https://stackoverflow.com/questions/62890408
复制相似问题