gpt4 book ai didi

javascript - 应用 javascript 检查文件大小和扩展名

转载 作者:数据小太阳 更新时间:2023-10-29 04:01:00 25 4
gpt4 key购买 nike

这是我的脚本。我想要做的是使用 onchange 事件触发它。但似乎效果不是很好。我试过在这里和那里编辑,但仍然面临问题。至于我在下面的最新编辑,问题是,有 2 个文件要上传,但只有第二个会显示警告消息,而第一个只会收到任何文件。

    <script>
function checkFile()
{
var node_list = document.getElementsByTagName('input');
for (var i = 0; i < node_list.length; i++)
{
var node = node_list[i];
if (node.getAttribute('type') == 'file')
{
var sFileName = node.value;
var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1];
var iFileSize = node.files[0].size;
var iConvert=(node.files[0].size/10485760).toFixed(2);
}


if (sFileExtension != "pdf" && sFileExtension != "doc" && sFileExtension != "docx" && iFileSize>10485760)
{
txt="File type : "+ sFileExtension+"\n\n";
txt+="Size: " + iConvert + " MB \n\n";
txt+="Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
alert(txt);
}
}
}
</script>

我的表格,

  <input type="file" name="file" id="confirm" onchange="checkFile()">
<input type="file" name="file" id="approveletter" onchange="checkFile()">

最佳答案

与其依赖元素本身,不如使用函数的给定事件来获取触发回调函数调用的文件。

传入事件将保证您实际上正在处理导致函数被调用的当前文件。

例如(我更改了变量名以使其更清楚):

ONLINE DEMO HERE

/// pass in event 
function checkFile(e) {

/// get list of files
var file_list = e.target.files;

/// go through the list of files
for (var i = 0, file; file = file_list[i]; i++) {

var sFileName = file.name;
var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
var iFileSize = file.size;
var iConvert = (file.size / 1048576).toFixed(2);

/// OR together the accepted extensions and NOT it. Then OR the size cond.
/// It's easier to see this way, but just a suggestion - no requirement.
if (!(sFileExtension === "pdf" ||
sFileExtension === "doc" ||
sFileExtension === "docx") || iFileSize > 10485760) { /// 10 mb
txt = "File type : " + sFileExtension + "\n\n";
txt += "Size: " + iConvert + " MB \n\n";
txt += "Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
alert(txt);
}
}
}

关于javascript - 应用 javascript 检查文件大小和扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18889948/

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