JavaScript: how to display the file size of an uploaded file using the File API

JavaScript: how to display the file size of an uploaded file using the File API

In this article we will see how to use the File API to get the size of a file and format it so that it is human readable.

File API is a powerful and versatile tool for handling files in JavaScript. One of their most useful features is the ability to read the size of a file uploaded with an upload form. In this article we will see how to use the File API to get the size of a file and format it so that it is human readable.

To use these APIs in JavaScript, we first need to grab the uploaded file from the upload form. We can do this by using the files property of the form's input element, which returns an array of File objects. For example, suppose we have a form with an input file with ID input-file. We get a reference to that element and then we can access its files property.

Once we have the file, we can use the size property of the File object to get the size of the file in bytes. However, the size in bytes may not be immediately understandable to users, therefore we may want to format it to make it more readable. For example, we may want to convert it to KB or MB.

To convert the size in bytes to KB or MB, we can use the following functions:


function bytesToKB(bytes) {
    return (bytes / 1024).toFixed(2) + ' KB';
}

function bytesToMB(bytes) {
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
}

Once we get the file size, we can display it in our upload form using the property innerHTML of the HTML element where we want to show the dimensions. To do this, we use the change event which will be triggered whenever the user selects a file.


const fileInput = document.getElementById('file-input');

fileInput.addEventListener('change', () => {
    const file = fileInput.files[0];
    const fileSize = file.size;
    const fileSizeKB = bytesToKB(fileSize);
    const fileSizeMB = bytesToMB(fileSize);
    const fileSizeElement = document.getElementById('file-size');
    fileSizeElement.innerHTML = `KB: ${fileSizeKB} - MB: ${fileSizeMB}`;
}, false);

In this way, we used the JavaScript File API to get and format the size of an uploaded file in an upload form. This feature is particularly useful when you want to provide users with an indication of the size of the file they are about to upload.