应用 javascript 检查文件大小和扩展名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18889948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Applying javascript to check file size and extension
提问by nanie
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.
这是我的脚本。我想要做的是使用 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>
my form,
我的表格,
<input type="file" name="file" id="confirm" onchange="checkFile()">
<input type="file" name="file" id="approveletter" onchange="checkFile()">
回答by
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):
例如(我更改了变量名称以使其更清晰):
/// 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);
}
}
}
回答by Prodigy
This might help
这可能有帮助
var file = document.getElementById("filex").files[0];
var filename = file.name;
var extSplit = filename.split('.');
var extReverse = extSplit.reverse();
var ext = extReverse[0];
if(!ext === "mp4" || !ext === "flv"){
alert('Accepted');
} else {
alert('Not accepted');
}
回答by Vishal Bhimani
you can used this code with file controller in html. any only pass parameter and see the output
您可以将此代码与 html 中的文件控制器一起使用。任何只传递参数并查看输出
<script type="text/javascript">
function AlertFilesize(cid,sz,a){
var controllerID = cid;
var fileSize = sz;
var extation = a;
if(window.ActiveXObject){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.getElementById('fileInput').value;
var thefile = fso.getFile(filepath);
var sizeinbytes = thefile.size;
}else{
var sizeinbytes = document.getElementById('fileInput').files[0].size;
}
var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}
var fup = document.getElementById('fileInput');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG")
{
var fs = Math.round(fSize);
if(fs < fileSize && fSExt[i] == extation)
{
alert("Image Successfully Uploaded");
return true;}else{
alert("Please enter the image size less then"+fileSize+extation);
document.getElementById('fileInput').value='';
return false;
}
}else{
alert("Must be jpg and gif images ONLY");
document.getElementById('fileInput').value='';
return false;}
}
</script>
<input id="fileInput" type="file" onchange="AlertFilesize(this.id,100,'KB');" />
回答by SAJID BRANE
<script type="text/javascript">
function setFileSize() {
var fileEl = document.getElementById('<%=FileUpload1.ClientID%>');
var fileSize = fileEl.files[0].size / 1024 / 1024;
var fileName = fileEl.files[0].name;
var dotPosition = fileName.lastIndexOf(".");
var fileExt = fileName.substring(dotPosition);
if (fileSize > 1) {
fileEl.value = '';
document.getElementById('<%=lblFileStatus.ClientID%>').innerHTML = 'File Should Be less Than 1MB';
return false;
}
}
回答by SAJID BRANE
<!DOCTYPE html>
<html>
<body>
<p>When you submit the form, a function is triggered which alerts some text.</p>
<form action="demo_form.asp" id="form">
Enter name: <input type="file" name="fname" id="form_file" onchange=" return myFunction()">
<input type="submit" value="Submit" id="submit">
</form>
<script>
function myFunction() {
var file = document.getElementById("form_file");
var file_name = file.value;
var extension = file_name.split('.').pop().toLowerCase();
var size = file.files[0].size;
var allowedFormats = ["jpeg", "jpg", "pdf", "tif"];
if(!(allowedFormats.indexOf(extension) > -1)){
alert("Enter a jpg/jpeg/pdf/tif file");
document.getElementById("submit").disabled = true;
return false;
} else if( ((size/1024)/1024) > 15){
alert("Your file should be less than 15MB");
return false;
} else {
document.getElementById("submit").disabled = false;
}
}
</script>
</body>
</html>
回答by Ronak Patel
take a look at this fiddle. It is working perfact. as i said there is change in your if condition.
看看这个小提琴。这是工作perfact。正如我所说,您的 if 条件发生了变化。
if (sFileExtension != "pdf" && sFileExtension != "doc" && sFileExtension != "docx" && iFileSize>10485760)
replace it with this
用这个替换它
if ((sFileExtension != "pdf" && sFileExtension != "doc" && sFileExtension != "docx") || iFileSize>10485760))