find the size of a file in javascript

To find the size of a file in JavaScript, you can use the File object's size property, which returns the size of the file in bytes. You can get the File object either by using the HTML5 File API or by uploading a file through a form.

Here is an example of getting the file size using the File object from an input field:

index.tsx
const fileInput = document.getElementById('file-input');
const fileSize = fileInput.files[0].size; // in bytes
console.log(fileSize);
134 chars
4 lines

Alternatively, you can also use FileReader API to get the size of a file as shown below:

index.tsx
const fileInput = document.getElementById('file-input');
const file = fileInput.files[0];
const reader = new FileReader();

reader.onloadend = function(event) {
  const fileSize = event.target.result.byteLength;
  console.log(fileSize);
};

reader.readAsArrayBuffer(file);
273 chars
11 lines

In the code above, FileReader reads the file content as an array buffer, and once the reading is complete, onloadend event is fired which contains the byte length of the file in event.target.result.byteLength.

related categories

gistlibby LogSnag