gpt4 book ai didi

html - 是否可以在 html5 中验证 input=file 的大小和类型

转载 作者:技术小花猫 更新时间:2023-10-29 11:40:19 26 4
gpt4 key购买 nike

我正在读这个http://dev.w3.org/html5/markup/input.file.html ,但我只找到了“accept”属性。

我试过了

<input type="file" name="imagefilename" accept="image/x-png, image/gif, image/jpeg" />

是否可以在客户端验证文件大小?

我为 IE 找到了这个技巧

<html>
<head>
<script>
function getSize()
{
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size + " bytes");
}
</script>
</head>
<body>
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onClick="getSize();">
</form>
</body>
</html>

是否可以使用 html5 filesystem api 来做同样的事情? ?

更新

我可以这样做(demo):

<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
<form >
<input type=file id=f max-size=32154 >
<input type=submit>
</form>
<script>
$(function(){
$('form').submit(function(){
var isOk = true;
$('input[type=file][max-size]').each(function(){
if(typeof this.files[0] !== 'undefined'){
var maxSize = parseInt($(this).attr('max-size'),10),
size = this.files[0].fileSize;
isOk = maxSize > size;
return isOk;
}
});
return isOk;
});
});
</script>
</body>

它工作正常,但我认为使用原生 html5 attr 进行验证会更好

最佳答案

    <form  class="upload-form">
<input class="upload-file" data-max-size="2048" type="file" >
<input type=submit>
</form>
<script>
$(function(){
var fileInput = $('.upload-file');
var maxSize = fileInput.data('max-size');
$('.upload-form').submit(function(e){
if(fileInput.get(0).files.length){
var fileSize = fileInput.get(0).files[0].size; // in bytes
if(fileSize>maxSize){
alert('file size is more then' + maxSize + ' bytes');
return false;
}else{
alert('file size is correct- '+fileSize+' bytes');
}
}else{
alert('choose file, please');
return false;
}

});
});
</script>

http://jsfiddle.net/9bhcB/2/

关于html - 是否可以在 html5 中验证 input=file 的大小和类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8212041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com