getting file size in javascript

Try this one.

function showFileSize() {
  let file = document.getElementById("file").files[0];
  if(file) {
    alert(file.size + " in bytes"); 
  } else { 
    alert("select a file... duh"); 
  }
}
<input type="file" id="file"/>
<button onclick="showFileSize()">show file size</button>

If it's not a local application powered by JavaScript with full access permissions, you can't get the size of any file just from the path name. Web pages running javascript do not have access to the local filesystem for security reasons.

HTML5 has the File API. If a user selects the file for an input[type=file] element, you can get details about the file from the files collection:

<input type=file id=fileSelector>
fileSelector.onchange = () => {
    alert(fileSelector.files[0].size);
}

If you could access the file system of a user with javascript, image the bad that could happen.

However, you can use File System Object but this will work only in IE:

http://bytes.com/topic/javascript/answers/460516-check-file-size-javascript


function findSize() {
    var fileInput =  document.getElementById("fUpload");
    try{
        alert(fileInput.files[0].size); // Size returned in bytes.
    }catch(e){
        var objFSO = new ActiveXObject("Scripting.FileSystemObject");
        var e = objFSO.getFile( fileInput.value);
        var fileSize = e.size;
        alert(fileSize);    
    }
}

Tags:

Javascript