Shixma
Shixma

Reputation: 425

Start a download with jquery or javascript?

I have some code that makes a button appear after the progress bar has gotten to the end. But I would prefer it if it started a download instead of someone having to click the button to download it. How would i go about doing this?

This is the code I'm currently using to open a button:

<script> 
$(document).ready(function() {
    $(".btn-success").hide();
    var progress = setInterval(function () {
        var $bar = $('.progress-bar');
        if ($bar.width() >= 399) {
            clearInterval(progress);
            $(".btn-success").show("slow");
            $('.progress').removeClass('active');
        } else {
            $bar.width($bar.width() + 40);
        }
    }, 115);
});
</script>
<div class="container">
    <div class="jumbotron" style="margin-top: 20px;">
        <h1 style="text-  align: center; margin-top: -5px;">Thanks for downloading!</h1>
        <h3 style="color: gray; text-  align: center; margin-top: -5px; margin-bottom: -20px;">Shixmas website source code</h3>  
    </div>
</div>

<div class="container" style="margin-top: 3%; width: 400px;">
    <div class="progress progress-striped active">
        <div class="progress-bar" style="width: 0%;"></div>
    </div>
    <div class="button_align_download">
        <a href="#"><button type="button" class="btn btn-success btn-lg">Download</button></a>
    </div>
</div>
<div class="container" style="margin-top: 3%;">
    <a href="/downloads">
        <button type="button" class="btn btn-default" style="margin-top:1%;">
            <span class="glyphicon glyphicon-chevron-left"></span>
            &nbsp;&nbsp;Go Back To Downloads
        </button>
    </a>
</div>

Upvotes: 0

Views: 272

Answers (1)

Ryan
Ryan

Reputation: 3926

The correct way to do this is to simply use window.location = '/downloads/file.jpg';

You then need to configure your server to send a header that instructs the browser to download that file instead of opening it in the window.

If you're using Apache you can add this to a .htaccess file. Using the following configuration, you can put all your downloads in the "downloads" folder and they will all download instead of opening.

This is just an example of course, you can set this up how you like.

<Location "/downloads/">
  <Files *.*>
    ForceType applicaton/octet-stream
    Header set Content-Disposition attachment
  </Files>
</Location>

Upvotes: 1

Related Questions