Read the source code selected for upload with JavaScript

In this article we will see a very simple solution to preview the source code uploaded in a form with JavaScript. This is a very practical solution in different contexts.

The FileReader class contains the readAsText() method that allows us to read the content of text files, that is, those files whose main MIME type is text (CSS, JavaScript, HTML, etc.).

We can create a function that handles the load event through a Promise and returns the textual content of the file:

function fileToText(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();

      reader.onload = () => resolve(reader.result);

      reader.onerror = () => reject;
      reader.readAsText(file);
    });
}

At this point, the file upload handling can be managed as follows:

function handleFile(input, preview) {
    input.addEventListener('change', async (e) => {
      preview.classList.remove('visible');
      const file =
        e.target.files && e.target.files.length > 0 ? e.target.files[0] : null;
      if (!file) {
        return;
      }
      const text = await fileToText(file);
      const codeBlock = preview.querySelector('code');
      codeBlock.innerText = text;
      preview.classList.add('visible');
    });
}

The upload form should still implement checks on the chosen MIME type in order to avoid errors when trying to read the content of unsupported files.

Demo

JavaScript Code Upload Preview

Conclusion

JavaScript has native APIs for reading the content of text files. This feature is very useful when we want to provide a preview of this type of file in a web interface.

Back to top