简体   繁体   中英

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. 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

The only thing that I can think of is to use those good ol' ActiveX objects:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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