File API in JavaScript - file data

- Andrés Cruz

En español
File API in JavaScript - file data

It is essential for web applications that handle a high volume of files when uploaded by the user; be able to validate or verify the file data that make up the file; before we had to upload the file so that from the server side perform these validations; It is now also possible to perform some of these validations on the client side with the Files API in JavaScript.

To date, some JavaScript APIs have been discussed that allow multiple functions to be carried out and that would be very difficult to do without them; now we will see how to work with part of the file API in JavaScript; We will see how you can obtain data from files that are loaded locally through the input type="file" and derivatives.

File API properties in JavaScript

Once the user performs the corresponding upload of the files, we can use the Files API in JavaScript to query data from the uploaded files; data such as extension, MIME, file size and thus easily validate that it has the specified format:

  • File.Name: Returns the name of the file (read only).
  • File.Size: Returns the size of the file (read only).
  • File.lastModifiedDate: Returns the last modification made to the file (read only).

EIn summary, the JavaScript file API allows you to perform a multitude of operations with any file that we can load images, plain text files, docs, etc.

Checking browser compatibility

Being a technology provided from the HTML5 API, it can undergo changes from one version to another of the browsers; therefore, it is necessary to validate that the browser really has the corresponding support for this API.

To verify compatibility we can use the following JavaScript code:

if (!(window.FileList)) {    console.log('La API FileList no está soportada');    return; }

The Filelist object is referenced even if it is not used directly by this name, it allows to return a list of the selected files (for example) in an input type="file".

Obtaining information on the constitution of the files

With browser support guaranteed, we can now be sure that the browser supports the properties listed above.

Getting access to user files

The most common method of loading files into an application is by using the input type="file" tag; once uploader with the help of the file API we can get a list of files uploaded by the user their information.

The file API 100% supports the multiples attribute present in the input type="file" tag.

Displaying the data of loaded files in a multiple input type="file"

The following example shows the different information obtainable through the API of files selected by a multiple input type="file":

if (!(window.FileList)) {
    console.log('La API FileList no está soportada');
    return;
}

var files = document.getElementById('files').files;

var output = [];
for (var i = 0, f; f = files[i]; i++) {
    output.push('<li>', escape(f.name), '(', f.type || 'n/a', ') - ',
            f.size, ' bytes, last modified: ',
            f.lastModifiedDate.toLocaleDateString(), '</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';

Example Download

Displaying loader file data using Drag and Drop

The following example is a variation of the previous one, and we can use the Drag and Drop to load the file and later show the information of the file:

    function drop(event) {
        event.stopPropagation();
        event.preventDefault();

        if (!(window.FileList)) {
            console.log('La API FileList no está soportada');
            return;
        }

        var files = event.dataTransfer.files;

        var output = [];
        for (var i = 0, f; f = files[i]; i++) {
            output.push('<li>', escape(f.name), '(', f.type || 'n/a', ') - ',
                    f.size, ' bytes, última modificación: ',
                    f.lastModifiedDate.toLocaleDateString(), '</li>');
        }
        document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
    }
    function dragenter(event) {

        event.stopPropagation();
        event.preventDefault();
    }

    function dragover(event) {
        event.stopPropagation();
        event.preventDefault();
    }

    var contenedor = document.getElementById("contenedor");

    contenedor.addEventListener("dragenter", dragenter, false);
    contenedor.addEventListener("dragover", dragover, false);
    contenedor.addEventListener("drop", drop, false);

Example Download

Conclusions

And this is all for now, we will continue talking about the files API later, exemplifying its use when we can not only list file information, but also open them for reading.

Links of interest

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.