DEV Community

Cover image for Calculating Maximum File Size Limit in JavaScript
Kamiswara Angga W.
Kamiswara Angga W.

Posted on • Updated on

Calculating Maximum File Size Limit in JavaScript

In modern JavaScript frameworks, when we upload a file, we usually create a function handler to handle if there is a change in the contents of the input file type. For example in Vue JS it's often like this:

async fileChange(e) {
  if (e.target.files[0].size / (1024 * 1024) > 10) {
    this.fileError = "File size is too large (max 10 MB)";
  } else {
    this.file = e.target.files[0];
  }
},
Enter fullscreen mode Exit fullscreen mode

The purpose of the code above is, if the selected file size is more than 10 MB, an error message will appear. If the file size is less than or equal to 10 MB, then the file will be put in state.


Why we need to calculate (1024 * 1024) in our code? Why don't we just replace the code with 1048576?

Because there are differences in file size calculations in different operating systems. For example, the calculation of file size in Windows is different from Ubuntu Linux.


File calculation in Windows:

Windows file calculation

File calculation in Ubuntu Linux:

Ubuntu Linux file calculation


Stackoverflow explanation

More on this matter:

https://askubuntu.com/questions/341143/why-same-file-shows-different-sizes-in-different-operating-systems

With this solution, the difference in calculations in different OS can be overcome, what do you think is the solution?

Top comments (0)