52

given a path of a file like:
C:\file.jpg
how can i get the size of the file in javascript?

2
  • code.google.com/p/gwtupload check this thing. They somehow manage to show uploading progress bar Commented Jun 3, 2010 at 17:52
  • 1
    Do you have a webserver able to access C:? If your OS is on C:, I advise against that, but first things first. Commented May 20, 2012 at 20:17

11 Answers 11

74

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);
}
Sign up to request clarification or add additional context in comments.

12 Comments

i think the same, but how some smart web applications show progress bar while uploading?
@Andrey: Other web applications use Java or Flash. I updated my answer with a link to the popular SWFUpload.
@Andrey Other script tools such as Flash, ActiveX, etc can access the local file system. Alternatively, certain server-side techniques can be used to monitor file upload progress and feed that information back when javascript requests it
check a link from another answer, scroll to end of page bytes.com/topic/javascript/answers/…
@Andrey: that is not a cross-browser solution either. I don't think Firefox exposes the fileSize property, it's certainly not part of the standard. It might also only work for valid images and not other files.
|
14
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);    
    }
}

2 Comments

can you add an explanation?
Oh, i guess the catch if for browsers that doesn't support the HTML5 way
6

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`

Comments

5

It's 2022 and of course this is possible by using fetch to get the file and returning a blob, then reading the size property of the returned blob. However this works if you run a local server, as it's not possible to access the local file system with Javascript (see the Note below).

function getFileStats(url){
  let fileBlob;
  fetch(url).then((res) => {
    fileBlob = res.blob();
    return fileBlob;
  }).then((fileBlob)=>{
    // do something with the result here
    console.log([fileBlob.size, fileBlob.type]);
  });
}

// Example of usage
getFileStats('http://127.0.0.1:5500/img/mobileset/1.jpg');

// You should get something like this in the console
[195142, 'image/jpeg']

Both the size and type properties have good browser coverage currently. Size is expressed in bytes, so roll your own formula to convert. This is just a quick example. It can be written better and adapted to your case. Processing a large number of files as blobs in the browser is likely to be a very compute-intensive task, especially for low-end computers, so use this accordingly.

Note: Javascript could never do this for a file on the local computer (at path C:\file.jpg) like in your example, because it's not supposed to do this by design. It would be a major security risk to allow web pages direct access to the local file system, it's only done through two filters: how the OS allows it through its API and how the browser allows it knowing that it needs to never expose the local file system to the internet. So my example will work if you run a server locally and can fetch the file through the server. Or if you fetch it from a remote server, if it allows.

Comments

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

Comments

2

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>

Comments

1

This is a pretty old question, but since it doesn’t seem to have an accepted answer yet I’ll chime in.

I concur that JavaScript is not the best way to get a file size. However, PowerShell (POSH) does it with ease. POSH even has a ready-made progress bar you can use to show the progress of an individual file being processed, or a group of files.

I’m uploading a file by FTP right now and watching the progress bar continuously update (courtesy of a .NET assembly from WinSCP). No need for a separate server side script to determine file sizes.

Comments

0

You can't get the file size of local files with javascript in a standard way using a web browser.

But if the file is accessible from a remote path, you might be able to send a HEAD request using Javascript, and read the Content-length header, depending on the webserver

3 Comments

i think the same, but how some smart web applications show progress bar while uploading?
@Andrey using flash or a php module which can count bytes or similar.
@Andrey there are module(s) for php to let you query the server to see how far the upload has progressed. I'm sorry but I don't remember the name. Also keep in mind that this could be stressful for the server as you keep querying it to see what the progress is. Flash has this counter on the clientside
0

You cannot.

JavaScript cannot access files on the local computer for security reasons, even to check their size.

The only thing you can do is use JavaScript to submit the form with the file field to a server-side script, which can then measure its size and return it.

2 Comments

It helps that you're answering from ten years in the future. When this question was asked in 2010, my answer as well as the more detailed answer accepted here were entirely correct. Browsers in 2010 did not allow JavaScript to read file sizes. Browsers in 2019 do. Let's revisit in 2030 and see if anything else has changed.
Good catch! Didn't look on the date. My mistake. Anyways. Nowdays JavaScript is as powerful as we can write it ourself, that is, if ther is a limit, it's probably because you just don't know how to solve it.
-1

You cannot as there is no file input/output in Javascript. See here for a similar question posted.

Comments

-1

To get the file size of pages on the web I built a javascript bookmarklet to do the trick. It alerts the size in kb's. Change the alert to a prompt if you want to copy the filesize.

Here's the bookmarklet code for the alert.

<a href="javascript:a=document.getElementsByTagName('HTML')[0].outerHTML;b=a.length/1024;c=Math.round(b);alert(c+' kb');">Doc Size</a>

Here's the bookmarklet code for the prompt.

<a href="javascript:a=document.getElementsByTagName('HTML')[0].outerHTML;b=a.length/1024;c=Math.round(b);prompt('Page Size',c+' kb');">Doc Size</a>

See it in action at http://bookmarklets.to.g0.to/filesize.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.