用jquery或javascript开始下载?

时间:2014-04-02 21:07:32

标签: javascript jquery download

我有一些代码可以在进度条结束后显示一个按钮。但我更喜欢它,如果它开始下载而不是有人必须单击按钮下载它。我该怎么做呢?

这是我目前用来打开按钮的代码:

<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>

1 个答案:

答案 0 :(得分:1)

正确的方法是使用window.location = '/downloads/file.jpg';

然后,您需要配置服务器以发送一个标题,指示浏览器下载该文件而不是在窗口中打开它。

如果您使用的是Apache,可以将其添加到.htaccess文件中。使用以下配置,您可以将所有下载内容放在“下载”文件夹中,它们将全部下载而不是打开。

这只是一个例子,当然,您可以根据自己的喜好进行设置。

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