JavaScript Download File From URL Programmatically

JavaScript Download File From URL
Project: Force File Download with JavaScript
Author: Daniel Watts
Edit Online: View on CodePen
License: MIT

This JavaScript code snippet creates a module named “fileDownload” that adds functionality to download a file from URL programmatically. It defines a function named “init” that is called to add an event listener to each element with class “js-download-link”. When a link is clicked, the code calls the “forceFileDL” function that handles the download of the file. This function performs checks on the user agent to determine whether the download can be initiated via a click event, and if not, it opens the file in a new window.

The module pattern ensures that the “init” function is only called once, and the functions and variables are contained within the module and are not global.

How to Download File From URL Programmatically in JavaScript

First of all, create an anchor tag with the class name “js-download-link” and place the link of the file inside the href attribute. You can place any file (i.e mp3, mp4, pdf, txt, jpg) that you want to download. The following is the basic HTML structure of a download page with various types of files:

<div class="wwdemo demo-body">
	<div class="demo-container">

 		<h1>Force a File to Download with Javascript</h1>

		<a class="js-download-link button" href="https://wattswork.s3.amazonaws.com/test-media/video/test_Drop-1280x720-16-9-HD.mp4">Download MP4 File</a>
		
		<a class="js-download-link button" href="https://wattswork.s3.amazonaws.com/test-media/PDFs/test-file.pdf">Download PDF File</a>
		
		<a class="js-download-link button" href="https://wattswork.s3.amazonaws.com/test-media/Text/test-file.txt">Download TXT File</a>
		
		<div class="demo-description">
			<p></p>
			<ul>
				<li>
					Downloads files without altering file headers.</li>
				</li>
				<li>Does not work on iOS devices.</li>
				<li>This method does not allow for renaming of files.</li>
			</ul>
		</div>
		
	</div>
</div>

Use the following CSS styles for the buttons and download page. These CSS rules are optional, you can define your own CSS according to your needs.

body
{
	padding: 0;
	margin: 0;
}

.wwdemo,
.wwdemo a
{
	font-family: Arial;
	color: #585858;
}

.wwdemo .demo-container
{
	background-color: #FFFFFF;
    width: 88%;
    margin: 2% auto;
    max-width: 40em;
    padding: 1.5% 3% 3%;
}

.wwdemo h1
{
	text-align: center;
	word-spacing: -0.1em;
   letter-spacing: -0.02em;
}

.wwdemo a.button
{
	-moz-box-shadow:inset 0px 1px 0px 0px #ffffff;
	-webkit-box-shadow:inset 0px 1px 0px 0px #ffffff;
	box-shadow:inset 0px 1px 0px 0px #ffffff;
	background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #ffffff), color-stop(1, #f6f6f6));
	background:-moz-linear-gradient(top, #ffffff 5%, #f6f6f6 100%);
	background:-webkit-linear-gradient(top, #ffffff 5%, #f6f6f6 100%);
	background:-o-linear-gradient(top, #ffffff 5%, #f6f6f6 100%);
	background:-ms-linear-gradient(top, #ffffff 5%, #f6f6f6 100%);
	background:linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f6f6f6',GradientType=0);
	background-color:#ffffff;
	-moz-border-radius:6px;
	-webkit-border-radius:6px;
	border-radius:0.22em;
	border:1px solid #dcdcdc;
	display:inline-block;
	cursor:pointer;
	color:#666666;
	font-family:Arial;
	font-size:15px;
	font-weight:bold;
	padding:19px 46px;
	text-decoration:none;
	text-shadow:0px 1px 0px #ffffff;
	margin: 2em auto;
	display: block;
	max-width: 12em;
	text-align: center;
}

.wwdemo a.button:hover
{
	background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #f6f6f6), color-stop(1, #ffffff));
	background:-moz-linear-gradient(top, #f6f6f6 5%, #ffffff 100%);
	background:-webkit-linear-gradient(top, #f6f6f6 5%, #ffffff 100%);
	background:-o-linear-gradient(top, #f6f6f6 5%, #ffffff 100%);
	background:-ms-linear-gradient(top, #f6f6f6 5%, #ffffff 100%);
	background:linear-gradient(to bottom, #f6f6f6 5%, #ffffff 100%);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f6f6f6', endColorstr='#ffffff',GradientType=0);
	background-color:#f6f6f6;
}

.wwdemo a.button:active
{
	position:relative;
	top:1px;
}

.demo-description
{
	font-size: 1.1em;
	line-height: 1.4em;
	margin: 2em 0;
}

Finally, add the following JavaScript function to download file from URL programmatically:

// jQuery module pattern enclosure.
var fileDownload = (function(){
	
	var classname = document.getElementsByClassName("js-download-link");

	function init()
	{
		for (var i = 0; i < classname.length; i++) {
			 classname[i].addEventListener('click', function( e ){
				e.preventDefault(); // Stops the normal element action.
				var attribute = this.getAttribute("href");
				window.forceFileDL( attribute );
			 }, false);
		}
	}

	window.forceFileDL = function( sUrl )
	{
		//iOS devices do not support downloading. We have to inform user about this.
		if (/(iP)/g.test(navigator.userAgent))
		{
			//alert('Your device does not support files downloading. Please try again in a desktop browser.');
			window.open(sUrl, '_blank');
			return false;
		}

		//If in Chrome or Safari - download via virtual link click
		if (window.forceFileDL.isChrome || window.forceFileDL.isSafari)
		{
			//Creating new link node.
			var link = document.createElement('a');
			link.href = sUrl;
			link.setAttribute('target','_blank');

			if (link.download !== undefined)
			{
				//Set HTML5 download attribute. This will prevent file from opening if supported.
				link.download = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
			}

			 //Dispatching click event.
			if (document.createEvent)
			{
				var e = document.createEvent('MouseEvents');
				e.initEvent('click', true, true);
				link.dispatchEvent(e);
				return true;
			}
		}

		// Force file download (if supported by server).
		if (sUrl.indexOf('?') === -1)
		{
			sUrl += '?download';
		}

		window.open(sUrl, '_blank');
		return true;
	}

   window.forceFileDL.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
   window.forceFileDL.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;

   return{
		init: init
	}
  
}());

fileDownload.init();

That’s all! hopefully, you have successfully integrated this code snippet to download files From URL. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply