简体   繁体   English

使用javascript查找文件上传中的文件大小

[英]find size of file in file upload using javascript

I want to size of file in file upload control. 我想在文件上传控件中调整文件大小。 I am getting error in Internet Explorer. 我在Internet Explorer中遇到错误。 But This is code working in other browser. 但这是在其他浏览器中运行的代码。 Following code 以下代码

var fuDocument = document.getElementById('<%= fupAttachment.ClientID %>');
  var file = fuDocument.files[0];
            if (file != null) {
                var fileSize = file.size;
}

error 'files.0' is null or not an object 错误“ files.0”为空或不是对象

The only thing that I can think of is to use those good ol' ActiveX objects: 我唯一想到的就是使用那些好的ActiveX对象:

var axFile = new ActiveXObject("Scripting.FileSystemObject");
var fileObj = axFile.getFile(document.getElementById('<%= fupAttachment.ClientID %>').value);
var fileSize = {bytes: fileObj.size,
                kBytes: Math.round(fileObj.size/1024),
                mBytes: Math.round((fileObj.size/1024)/1024)};

That should offer support for older versions of IE, the full version could look something like: 这应该为IE的较早版本提供支持,完整版可能如下所示:

var axFile, fileSize, 
fuDocument = document.getElementById('<%= fupAttachment.ClientID %>');
if (fuDocument.files)
{
    fileSize = fuDocument.files[0].size || 0;//default value = 0
}
else
{
    axFile = new ActiveXObject("Scripting.FileSystemObject");
    fileSize = (axFile.getFile(fuDocument.value) || {size:0}).size;//default to object literal, with size: 0 property --> avoids errors, and defaults to size value of zero
}
return fileSize;//console.log, alert... whatever you want

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM