javascript - 带有扩展名和文件大小的 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">
解决方案
使用 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')
}
})
推荐阅读
- clang - 如何配置 GN(Google 的 generate-ninja)/Ninja 以使用不同的 clang 工具链
- python - 在 python 中使用 boto3 查询 cloudwatch 日志以获取不同的值
- python - Numpy矢量化函数
- vue.js - v-for range 循环中的多个 vuetify 生日选择器
- sql - 要在另一个模型中按日期字段分组的模型对象
- javascript - 如何从 JS for 循环中获取数组?
- sql - 使用 Haskell 的 postgres-simple 库执行多行插入时,如何修复“运算符不存在:text = uuid”?
- python - 如何在 python libtorrent 中使用 IP_FILTER
- xml - 未指定时的默认 XML 架构/XSD?
- java - Android Studio [代码] -> [将 Java 文件转换为 Kotlin 文件] 不适用于大文件