最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Start downloading file using JQuery - Stack Overflow

programmeradmin3浏览0评论

I want to start file downloading when I clicked the button.
I just have the path of the file.
How can I start downloading?
This is what I tried so far:

$('#download_button').click(function(){

    var filepath = $(this).attr('data-filepath');
    var do = '<a href="'+ filepath +'" download="file">file</a>';
    $(body).append(do);
});

What I am doing wrong.
I never want to redirect the page.
Is downloading start in browser or in software for downloading files if installed on client machine

I want to start file downloading when I clicked the button.
I just have the path of the file.
How can I start downloading?
This is what I tried so far:

$('#download_button').click(function(){

    var filepath = $(this).attr('data-filepath');
    var do = '<a href="'+ filepath +'" download="file">file</a>';
    $(body).append(do);
});

What I am doing wrong.
I never want to redirect the page.
Is downloading start in browser or in software for downloading files if installed on client machine

Share Improve this question edited May 1, 2014 at 10:41 csharpwinphonexaml 3,68310 gold badges33 silver badges64 bronze badges asked May 1, 2014 at 10:16 user3316523user3316523 6503 gold badges11 silver badges15 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

Alternatively you can also set the top.location

$('#download_button').click(function(){
    var filepath = $(this).attr('data-filepath');
    top.location.href = filepath;
});

You cannot force a file to be downloaded in JavaScript.

What you can do is location.href = "somefile.ext";, however it will only be downloaded if the server includes Content-Disposition: attachment as one of its response headers to that file request.

If you want to download a file to the client, then do this:

$('#download_button').click(function(){
    var filepath = $(this).attr('data-filepath');
    location.href = filepath;
});

location.href will look for a page, but it will not find anything, so it will download the file instead.

You can create a form using jQuery and use the submit function. This will not change the URL in the address bar.

$('#download_button').click(function(){

        var filepath = $(this).attr('data-filepath');
        var form = $('<form>').attr('action', filepath);
        form.submit();
});
发布评论

评论列表(0)

  1. 暂无评论