DEV Community

Kamiswara Angga W.
Kamiswara Angga W.

Posted 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 ([0].size / (1024 * 1024) > 10) {
    this.fileError = "File size is too large (max 10 MB)";
  } else {
    this.file =[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:

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

Top comments (0)


11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!