Search Here

Javascript Multiple Files Preview using createObjectURL and FileReader

Javascript Multiple Files Preview using createObjectURL and FileReader

Displaying the preview of the file uploaded is the most common feature we see on websites. This will make it easier for the client to see which file he has selected. We’ll be doing the same thing in this post where the files selected by the user are displayed in HTML as a preview.

In Javascript, there are various ways to preview files but in this post, we’ll cover two ways. The first is using URL.createObjectURL() method and second is using FileReader with promise.

You can learn more about Javascript createObjectURL() method by clicking here.

Multiple File Preview Using URL.createObjectURL() method

One of the easiest ways of displaying image preview as it requires only a single line of code to be written. The createObjectURL() method returns a URL of the blob file. It takes a single argument which is a file object.

The sample output of the createObjectURL() method is shown below.

blob:null/dc704079-9482-4881-9e3d-86872012238f

We’ll be using this in the example below.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple File Preview using createObjectURL method</title>
    <style>
        .img-small{
            width: 100px;
            height: auto;
        }

        #image-template{
            display: flex;
        }
    </style>
</head>
<body>
    <div id="image-template"></div>

    <input onchange="show_file_previews( event )" type="file" id="file" multiple  >


    <script>
        let image_template = document.getElementById('image-template');
        
        let icons_url = {
            'xlsx' : 'https://img.icons8.com/color/48/000000/ms-excel.png',
            'pdf' : 'https://img.icons8.com/color/50/000000/pdf.png',
            'docx' : 'https://img.icons8.com/color/48/000000/word.png',
        };

        function get_extenstion( file ){
            return file.name.split( "." )[1];
        }


        function show_file_previews( e ){
            let file_element = e.target;
            let files = e.target.files;
            let object_url = null, div = null, extension=null;

            image_template.innerHTML = "";
            if( files.length ){
                for( let index in files ){

                    if( files[index] instanceof File ){                 
    
                        extension = get_extenstion( files[index] );
                        object_url = ( icons_url[extension] )? icons_url[extension]:  URL.createObjectURL( files[index] );
    
                        div = document.createElement('DIV');
                        div.innerHTML = `
                            <img src="${object_url}" class="img-small" >
                        `;
                        image_template.appendChild( div );
                    }

                }
            }
        }
    </script>
</body>
</html>
Multiple Files Preview  Using URL.createObjectURL() method

Multiple Files Preview Using URL.createObjectURL() method

Preview of Output

Multiple File Preview Using FileReader Object

The FileReader lets you store file contents on the client’s computer. It lets you output files as text or URLs. This makes an ideal solution to use for previewing
files and images. Apart from this, it can be used for other purposes also such as storing textual or binary information.

We will be using readAsDataURL( <blob_file> ) the method which takes a file as an argument and returns a URL of that file. The output will be received in the .result property of the file object.

Sync the FileReader works asynchronously we have to specify a onload() function to get the output.

Note

During multiple file previews, the FileReader onload() function tends to overwrite the previous ones. The best way to avoid this is to use a promise to read file contents.

You can learn more about Javascript FileReader by clicking here.

Below is an example of a preview image using the FileReader object.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple File Preview using FileReader Object</title>
    <style>
        .img-small{
            width: 100px;
            height: auto;
        }

        #image-template{
            display: flex;
        }
    </style>
</head>
<body>
    <div id="image-template"></div>

    <input onchange="show_file_preview_using_file_reader( event )" type="file" id="file" multiple  >


    <script>
        let image_template = document.getElementById('image-template');
        
        let icons_url = {
            'xlsx' : 'https://img.icons8.com/color/48/000000/ms-excel.png',
            'pdf' : 'https://img.icons8.com/color/50/000000/pdf.png',
            'docx' : 'https://img.icons8.com/color/48/000000/word.png',
        };

        function get_extenstion( file ){
            return file.name.split( "." )[1];
        }


        function show_file_previews( e ){
            let file_element = e.target;
            let files = e.target.files;
            let object_url = null, div = null, extension=null;

            image_template.innerHTML = "";
            if( files.length ){
                for( let index in files ){

                    if( files[index] instanceof File ){                 
    
                        extension = get_extenstion( files[index] );
                        object_url = ( icons_url[extension] )? icons_url[extension]:  URL.createObjectURL( files[index] );
    
                        div = document.createElement('DIV');
                        div.innerHTML = `
                            <img src="${object_url}" class="img-small" >
                        `;
                        image_template.appendChild( div );
                    }

                }
            }
        }
    </script>
    <script>
        let file_promise = file => new Promise( ( resolve, reject ) => {
            reader = new FileReader();
            reader.readAsDataURL( file );
            reader.onload = function(){
                resolve(reader.result);
            }
        } );

        async function show_file_preview_using_file_reader( e ){
            
            let file_element = e.target;
            let files = e.target.files;
            let object_url = null, div = null, reader=null, extension=null;
            
            image_template.innerHTML = "";
            if( files.length ){
                for( let index in files ){

                    if( files[index] instanceof File ){

                            extension = get_extenstion( files[index] );
    
                            object_url = ( icons_url[extension] )? icons_url[extension]:  await file_promise( files[index] );

                            div = document.createElement('DIV');
                            div.innerHTML = `
                                <img src="${object_url}" class="img-small" >
                            `;
                            image_template.appendChild( div );
                        }
                    }

            }
        }

    </script>
</body>
</html>

Preview of Output

Apart from image files if you upload non-image files then it will show the icon instead of an image as all the icon URLs are store in the icons_url object.

Watch Video

Summary
Review Date
Reviewed Item
Javascript Multiple Files Preview using createObjectURL and FileReader
Author Rating
51star1star1star1star1star
Software Name
Javascript Programming
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development