问题描述
这是我的脚本。我想要做的是使用onchange事件触发它。
但似乎效果不好。我曾尝试过编辑,但仍面临问题。至于我下面的最新编辑,问题是,有2个文件要上传,但只有第二个会显示警告信息,而第一个文件只会收到任何文件。
here is my script. What I am trying to do is to trigger it using onchange event.But it seems does not work very well. I have tried edit here and there but still facing problems. As for my latest edit below, the problem is, there is 2 files to be uploaded, but only the second one will display alert message, while the first one will just receive any file.
<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()">
推荐答案
您应该使用自己的元素而不是依赖它们函数的给定事件,以获取触发调用回调函数的文件。
Rather than relying on the elements them self you should use the given event to the function to get the file(s) that triggered the call to the callback function.
传递事件将保证您实际上正在使用导致函数被调用的当前文件。
Passing in the event will guarantee you that you are actually working with the current files that caused the function to be called.
例如(我更改了变量名以使其更清晰):
For example (I changed the variable name to make it more clear):
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检查文件大小和扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!