getting file size in javascript

Solution 1:

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.

You can use a graceful degrading file uploader like SWFUpload if you want to show a progress bar. HTML5 also has the File API, but that is not widely supported just yet. If a user selects the file for an input[type=file] element, you can get details about the file from the files collection:

alert(myInp.files[0].size);

Solution 2:

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);    
    }
}

Solution 3:

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

Solution 4:

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>

Solution 5:

You could probably try this to get file sizes in kB and MB Until the file size in bytes would be upto 7 digits, the outcome would be in kbs. 7 seems to be the magic number here. After which, if the bytes would have 7 to 10 digits, we would have to divide it by 10**3(n) where n is the appending action . This pattern would repeat for every 3 digits added.

let fileSize = myInp.files[0].size.toString();

if(fileSize.length < 7) return `${Math.round(+fileSize/1024).toFixed(2)}kb`
    return `${(Math.round(+fileSize/1024)/1000).toFixed(2)}MB`