Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Javascript Download.js Library Example to Download Files From URL as Attachment in Browser

Posted on October 1, 2022

 

 

Welcome folks today in this blog post we will be talking about a new javascript library called as download.js library which lets the user downloads the files such as images,pdf and videos from url as an attachment inside the browser.

 

 

Installation

 

 

Now to install this library there are various options available. If you want to use in the browser using javascript you can use the cdn link and include it inside the html as shown below

 

index.html

 

 

1
2
3
4
5
6
7
8
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Download.js CDN Example in Browser</title>
    <script src='//js.zapjs.com/js/download.js'></script>
</head>
</html>

 

 

The second option is to use at the node.js server side. You can install it as a module by executing the below command

 

 

1
npm i downloadjs

 

 

Third option is very simple you can create downloadfile.js and copy paste the entire code of the library which is shown below

 

downloadfile.js

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
<script>//download.js v4.2, by dandavis; 2008-2016. [CCBY2] see http://danml.com/download.html for tests/usage
// v1 landed a FF+Chrome compat way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
// v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
// v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.
// v4 adds AMD/UMD, commonJS, and plain browser support
// v4.1 adds url download capability via solo URL argument (same domain/CORS only)
// v4.2 adds semantic variable names, long (over 2MB) dataURL support, and hidden by default temp anchors
// https://github.com/rndme/download
 
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.download = factory();
  }
}(this, function () {
 
return function download(data, strFileName, strMimeType) {
 
var self = window, // this script is only for browsers anyway...
defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
mimeType = strMimeType || defaultMime,
payload = data,
url = !strFileName && !strMimeType && payload,
anchor = document.createElement("a"),
toString = function(a){return String(a);},
myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
fileName = strFileName || "download",
blob,
reader;
myBlob= myBlob.call ? myBlob.bind(self) : Blob ;
  
if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
payload=[payload, mimeType];
mimeType=payload[0];
payload=payload[1];
}
 
 
if(url && url.length< 2048){ // if no filename and no mime, assume a url was passed as the only argument
fileName = url.split("/").pop().split("?")[0];
anchor.href = url; // assign href prop to temp anchor
   if(anchor.href.indexOf(url) !== -1){ // if the browser determines that it's a potentially valid url path:
         var ajax=new XMLHttpRequest();
         ajax.open( "GET", url, true);
         ajax.responseType = 'blob';
         ajax.onload= function(e){
  download(e.target.response, fileName, defaultMime);
};
         setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return:
    return ajax;
} // end if valid url?
} // end if url?
 
 
//go ahead and download dataURLs right away
if(/^data\:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)){
if(payload.length > (1024*1024*1.999) && myBlob !== toString ){
payload=dataUrlToBlob(payload);
mimeType=payload.type || defaultMime;
}else{
return navigator.msSaveBlob ?  // IE10 can't do a[download], only Blobs:
navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
saver(payload) ; // everyone else can save dataURLs un-processed
}
}//end if dataURL passed?
 
blob = payload instanceof myBlob ?
payload :
new myBlob([payload], {type: mimeType}) ;
 
 
function dataUrlToBlob(strUrl) {
var parts= strUrl.split(/[:;,]/),
type= parts[1],
decoder= parts[2] == "base64" ? atob : decodeURIComponent,
binData= decoder( parts.pop() ),
mx= binData.length,
i= 0,
uiArr= new Uint8Array(mx);
 
for(i;i<mx;++i) uiArr[i]= binData.charCodeAt(i);
 
return new myBlob([uiArr], {type: type});
}
 
function saver(url, winMode){
 
if ('download' in anchor) { //html5 A[download]
anchor.href = url;
anchor.setAttribute("download", fileName);
anchor.className = "download-js-link";
anchor.innerHTML = "downloading...";
anchor.style.display = "none";
document.body.appendChild(anchor);
setTimeout(function() {
anchor.click();
document.body.removeChild(anchor);
if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(anchor.href);}, 250 );}
}, 66);
return true;
}
 
// handle non-a[download] safari as best we can:
if(/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
url=url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
if(!window.open(url)){ // popup blocked, offer direct download:
if(confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")){ location.href=url; }
}
return true;
}
 
//do iframe dataURL download (old ch+FF):
var f = document.createElement("iframe");
document.body.appendChild(f);
 
if(!winMode){ // force a mime that will download:
url="data:"+url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
}
f.src=url;
setTimeout(function(){ document.body.removeChild(f); }, 333);
 
}//end saver
 
 
 
 
if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
return navigator.msSaveBlob(blob, fileName);
}
 
if(self.URL){ // simple fast and modern way using Blob and URL:
saver(self.URL.createObjectURL(blob), true);
}else{
// handle non-Blob()+non-URL browsers:
if(typeof blob === "string" || blob.constructor===toString ){
try{
return saver( "data:" +  mimeType   + ";base64,"  +  self.btoa(blob)  );
}catch(y){
return saver( "data:" +  mimeType   + "," + encodeURIComponent(blob)  );
}
}
 
// Blob but not URL support:
reader=new FileReader();
reader.onload=function(e){
saver(this.result);
};
reader.readAsDataURL(blob);
}
return true;
}; /* end download() */
}));</script>

 

 

Usage

 

 

Now to use this library in an actual web application we will be using html and javascript So just create a index.html file and inside this file we have a simple input field where the user can enter the url of the file to be downloaded and a button to trigger the action.

 

 

index.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!doctype html>
<html>
 
<head>
    <meta charset="UTF-8">
    <title>Download Image Demo</title>
    <style>
        body {
            font: menu;
        }
    </style>
    <script src='//js.zapjs.com/js/download.js'></script>
</head>
 
<body>
    <h1>Download Image File Demo using download.js</h1>
    <input type="url" id="url" required/>
    <button id="download">Download</button>
</body>
</html>

 

 

Now if you open the index.html file inside the browser you will see a input field where the user can enter the path of the file to be downloaded

 

 

Now we need to write the javascript code when we click the button what should happen

 

 

script.js

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
document.getElementById('download').addEventListener('click',(e) => {
        let url = document.getElementById('url').value
        downloadFile(url)
    })
    function downloadFile(url){
 
        var x = new XMLHttpRequest();
        x.open("GET", url, true);
        x.responseType = 'blob';
        x.onload = function (e) {
            // the name of the file and mime type can be skipped
            download(x.response, "dlBinAjax.png", "image/png");
        }
        x.send();
    }

 

 

So here guys we are also using some ajax to initiate the request to download the image and then we are using the download library method passing the url and the actual file name and the extension of the file in this case it is png image file.

 

Now if you click the button a png image file will be downloaded as an attachment as shown below in the picture

 

 

 

Recent Posts

  • Android Java Project to Build MP4 Video to MP3 Audio Converter Using MediaMuxer Class
  • Android Java Project to Merge Multiple PDF Documents From Gallery Using iTextPDF Library
  • Android Java Project to Detect System Hardware & System CPU Info & Display inside TextView Widget
  • Android Java Project to Integrate Google OAuth2 Login & Logout System & Save User Info in SharedPreferences
  • Android Java Project to Export Raw Text to PDF Document Using iTextPDF Library
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme