Fox
Fox

Reputation: 141

How can I download a file automatically without click on button?

I am trying to write code that opens a clean page that downloads a file when I open it. My problem is that I didn't find how to do it automatically. I only find this code:

<!DOCTYPE html>
<html>
<body>
<a href="content/file.jpg" download > jpg link </a>
</body>
</html>

Upvotes: 6

Views: 25229

Answers (4)

Ernest Larbi
Ernest Larbi

Reputation: 1

I was struggling with this same issue and finally figured out this using jquery. This code uses jquery's $(document).ready(function () to run automatically.

<script type="text/javascript">
        $(document).ready(function () {
            var downloadLink = document.createElement('a');
            downloadLink.style.display = 'none';
            document.body.appendChild(downloadLink);
            downloadLink.href = 'myFile.txt';
            downloadLink.click();
        });
    </script>

Replace myFile.txt with the file you want to autodownload. Add this to the header section of your html page. Any file format can be added! You can follow for more at www.youtube.com/@cipherTechWisdom . Cheers!

Upvotes: 0

Hassan Farooqstar
Hassan Farooqstar

Reputation: 23

I have a Solution. But it's just a trick. I use to do spamming in my university web-based Chat room by using this TRICK, all active chat room users will get my file :p hehe .

Download file without clicking using Pure HTML.

Syntax:

<iframe src="Paste your direct download link here" ></iframe>

For Example:

<iframe src="https://download-installer.cdn.mozilla.net/pub/firefox/releases/98.0.2/win32/en-US/Firefox%20Installer.exe" ></iframe>

As the browser reloads your download will be triggered automatically.

NOTE: This won't work on images. This trick only works on videos, exe, audio, etc

Upvotes: 1

sansan
sansan

Reputation: 833

I hope this will works all the browsers. You can also set the auto download timing.

<html>
<head>
<title>Start Auto Download file</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function() {
$('a[data-auto-download]').each(function(){
var $this = $(this);
setTimeout(function() {
window.location = $this.attr('href');
}, 2000);
});
});
</script>
</head>
<body>
<div class="wrapper">
<p>The download should start shortly. If it doesn't, click
<a data-auto-download href="auto-download.zip">here</a>.</p>
</div>
</body>
</html>

Demo Here

Upvotes: 2

Without using a backend language, you can add this jQuery to your HTML document.

<script type="text/javascript">
    $(document).ready(function () {

        $("a").click();

    });
</script>

The link will be automatically clicked as soon as the document has loaded.

Upvotes: 3

Related Questions