getting file size in javascript
Asked Answered
G

11

49

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

Gocart answered 3/6, 2010 at 12:52 Comment(2)
code.google.com/p/gwtupload check this thing. They somehow manage to show uploading progress barJenifferjenilee
Do you have a webserver able to access C:? If your OS is on C:, I advise against that, but first things first.Lacour
E
70

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);
}
Earpiece answered 3/6, 2010 at 12:56 Comment(12)
i think the same, but how some smart web applications show progress bar while uploading?Jenifferjenilee
@Andrey: Other web applications use Java or Flash. I updated my answer with a link to the popular SWFUpload.Earpiece
@Jenifferjenilee 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 itChihuahua
check a link from another answer, scroll to end of page bytes.com/topic/javascript/answers/…Jenifferjenilee
@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.Earpiece
@Andy E's head - you convinced me :)Jenifferjenilee
@Andy E's head i am back. go to gmail and add attachment to letter. you see progress bar? there is no flash! please explainJenifferjenilee
@Andrey: They probably use an application similar to GWTUpload, which queries the server for the file progress. This is a suitable method, but it obviously puts more strain on the server.Earpiece
@Andy E's head E's head progress is equal to total size / uploaded size, so did they manage to measure total size?Jenifferjenilee
@Andrey: The browser sends the total file size along with the multipart headers, so it's fairly easy to procure the total from those headers.Earpiece
@Andy E's head now i know what to do! get headers on server and drop transfer of body :) thank you for explanationJenifferjenilee
Nowadays (2022) pretty much every browser worthy of mention supports the File Api (caniuse.com/fileapi)Tauromachy
T
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);    
    }
}
Thermy answered 30/1, 2013 at 15:11 Comment(2)
can you add an explanation?Collateral
Oh, i guess the catch if for browsers that doesn't support the HTML5 wayEire
S
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`
Statocyst answered 22/7, 2020 at 11:0 Comment(0)
C
4

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.

Credulous answered 2/5, 2022 at 3:35 Comment(0)
U
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

Up answered 3/6, 2010 at 12:58 Comment(0)
G
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>
Genniegennifer answered 1/12, 2017 at 18:53 Comment(0)
A
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.

Allisonallissa answered 29/8, 2023 at 0:20 Comment(0)
M
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

Middleaged answered 3/6, 2010 at 12:55 Comment(3)
i think the same, but how some smart web applications show progress bar while uploading?Jenifferjenilee
@Jenifferjenilee using flash or a php module which can count bytes or similar.Middleaged
@Jenifferjenilee 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 clientsideMiddleaged
H
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.

Hers answered 3/6, 2010 at 12:57 Comment(2)
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.Hers
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.Catch
S
-1

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

Stenograph answered 3/6, 2010 at 12:57 Comment(0)
Q
-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

Quickfreeze answered 12/5, 2013 at 23:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.