如何使用jquery下载文件?

时间:2023-02-06 00:28:54

I have to download a file (pdf/zip/txt ...) using jquery.

我必须使用jquery下载文件(pdf / zip / txt ...)。

What i tried ??

我试过了什么?

<a href="abc.pdf">click</a>

When i click the link the file is opened in browser.

当我点击链接时,文件在浏览器中打开。

using jquery...

$('a').click(function(e)
{
e.preventDefault();
var link = $(this).attr('href');
window.location = link;
});

This also leads to open the file in browser. But i want to download it not display in browser.

这也导致在浏览器中打开文件。但我想下载它不在浏览器中显示。

In PHP we can use header('Content-Disposition: attachment; filename="test.mp3"');

在PHP中我们可以使用header('Content-Disposition:attachment; filename =“test.mp3”');

But i have to use only jquery/javascript..

但我必须只使用jquery / javascript ..

1 个解决方案

#1


8  

You can trigger a download by using the new HTML5 download attribute.

您可以使用新的HTML5下载属性触发下载。

<a href="path_to_file" download="proposed_file_name">Download</a>

path_to_file is either an absolute or relative path, proposed_file_name the filename to save to (can be blank, then defaults to the actual filename).

path_to_file是绝对路径或相对路径,proposed_file_name是要保存的文件名(可以是空白,然后默认为实际文件名)。

#1


8  

You can trigger a download by using the new HTML5 download attribute.

您可以使用新的HTML5下载属性触发下载。

<a href="path_to_file" download="proposed_file_name">Download</a>

path_to_file is either an absolute or relative path, proposed_file_name the filename to save to (can be blank, then defaults to the actual filename).

path_to_file是绝对路径或相对路径,proposed_file_name是要保存的文件名(可以是空白,然后默认为实际文件名)。