javascript 开始使用 JQuery 下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23405778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:50:06  来源:igfitidea点击:

Start downloading file using JQuery

javascriptjquery

提问by user3316523

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

我做错了什么。
我从不想重定向页面。
如果安装在客户端计算机上,是在浏览器或用于下载文件的软件中开始下载

回答by Rob Schmuecker

Alternatively you can also set the top.location

或者,您也可以设置 top.location

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

回答by Niet the Dark Absol

You cannot force a file to be downloaded in JavaScript.

您不能强制使用 JavaScript 下载文件。

What you can do is location.href = "somefile.ext";, however it will onlybe downloaded if the serverincludes Content-Disposition: attachmentas one of its response headers to that file request.

您可以做的是location.href = "somefile.ext";,但是只有服务器包含Content-Disposition: attachment该文件请求的响应标头之一时才会下载它。

回答by Amit Joki

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.hrefwill look for a page, but it will not find anything, so it will download the file instead.

location.href将查找一个页面,但找不到任何内容,因此它将下载文件。

回答by Oday Fraiwan

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

您可以使用 jQuery 创建表单并使用提交功能。这不会更改地址栏中的 URL。

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

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