List and Download files Using Pure Javascript (XAMPP on windows)

 List and Download files Using Pure Javascript 

(XAMPP on windows)





Create a folder inside your project by the name of downloads and add some files to it.

HTML CODE


<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>List & Download Files Using JS</title>

    <style>
         :root {
            --border: #aaa;
            --padding-1x: 5px;
            --padding-2x: 10px;
        }
       
        body {
            font-family: monospace;
            padding: 10%;
        }
       
        h1,
        h2 {
            text-align: center;
        }
       
        .table {
            border-collapse: collapse;
            width: 100%;
        }
       
        .table tr {
            border-bottom: 1px solid var(--border);
        }
       
        .table tr td {
            padding: var(--padding-2x);
        }
    </style>
</head>

<body>
    <h1>List and Download files Using Pure Javascript</h1>
    <h2>(XAMPP on Windows)</h2>
    <table id="files-table" class="table">
        <thead>
            <tr>
                <th>#</th>
                <th>Files</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <script>
        var directory = "downloads";
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open('GET', directory, false);
        xmlHttp.send(null);
        var ret = xmlHttp.responseText;
        var fileList = ret.split('\n');
        let html = "";
        let ind = 1;
        for (i = 0; i < fileList.length; i++) {
            if (fileList[i].includes('href')) {
                let flParts = fileList[i].split('href="');
                let flFinal = flParts[1].split('"');
                if (flFinal[0] != "?C=N;O=D" && !(flFinal[0].includes("/"))) {
                    html += `<tr><td>${ind}</td><td>${flFinal[0]}</td><td><a href="${directory}/${flFinal[0]}" download="${flFinal[0]}">Download</a></td><tr>`;
                    ind += 1;

                }
            }
        }
        document.querySelector("#files-table tbody").innerHTML = html;
    </script>
</body>

</html>




See the Pen List and Download files Using Pure Javascript (XAMPP on windows) by Muhammad Habib (@mhabib555) on CodePen.

Comments

Popular posts from this blog

JS-QR Generator

Input Mask Using Libraries

PHP -Sending Email from Localhost (XAMPP) Using SendinBlue