首页 > 解决方案 > 带有扩展名和文件大小的 JavaScript 文件类型

问题描述

亲爱的先生,这段代码工作正常。但我需要使用文件类型扩展名和文件大小进行 JavaScript 验证。当我同时上传文件时,它会检查文件大小和文件扩展名,以便产生所需的结果。请帮助我更正代码将感谢你。期待积极的回应

$('#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">

标签: javascriptjqueryajax

解决方案


使用 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')
}
        })

推荐阅读