kessi-cpa Library logo (4.0 KB)

How to Download Documents From a Server on a Click

Concept

In some cases, you would want your website visitors to be able to download documents such as PDF or Microsoft Word just by clicking on a button or a link. Each browser handles the download function differently; however, they will all download the document to the client’s computer. In general, it will be downloaded to the 'Download' folder.

In this tutorial, we will use a button and a link to trigger the download of a PDF document.

First, make sure the document is available for download by adding it to the Root Folder of your website.

In my case, I created a sub-folder in my Root folder and named it 'Demos', and in this sub-folder I created another sub-folder and named it 'Documents', and then, inside this sub-folder, I created a pdf document and named 'Test.pdf'. The href for the link is the complete address of the Test.pdf document including the extension.

Note: for the download icon in the button example to properly display, you have to insert the following link in the head section of your page ("Font Awesome by Dave Gandy - http://fontawesome.io):
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>

Example: Using a link

Click on the link below to download the pdf document:

How To

1. Add HTML

2. Add CSS



Example: Using a button

How To

1. Add HTML

<button class="btn" onclick="downloaddoc()">
   <i class="fa fa-download" style="font-size:25px; margin-right:10px;"></i>DOWNLOAD
</button>
<a id="aDownload" href="https://www.kessitek.com/Demos/Documents/Test.pdf" class="lnk"></a>

2. Add CSS

.btn
{
    height: 50px;
    width: 180px;
    border: none;
    border-radius: 3px;
    background-color: #009933;
    background-image: -webkit-linear-gradient(top,#00e64d,#009933);
    cursor: pointer;
    color: #fff;
    font-size: 16px;
    transition: 0.4s;
}

.btn:hover
{
    background-color: #00cc44;
    background-image: -webkit-linear-gradient(top,#1aff66,#00cc44);
}

.lnk
{
    display: none;
}

3. Add JavaScript

<script type="text/javascript">
    function downloaddoc() {
        try {
            document.getElementById("aDownload").click();
        }
        catch (err) {
            window.alert(err.message);
        }
    }
</script>
js for dialogbox (39 kb)
Author of this article:
Mahmoud Kessi, CPA, CGA
mkessi@kessi-cpa.com
(204) 226-9576

Comments & Questions

Add New Comment or Question




Post

REPLY/COMMENT



Email Link


Link to be shared:

×

Confirmation

Copyright © 2016-2019 KESSITEK.