使用 Javascript/jQuery 下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3749231/
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-08-23 05:59:26  来源:igfitidea点击:

Download File Using Javascript/jQuery

javascriptjquerydownload

提问by Mithun Sreedharan

I have a very similar requirement specified here.

在此处指定一个非常相似的要求。

I need to have the user's browser start a download manually when $('a#someID').click();

我需要让用户的浏览器手动开始下载 $('a#someID').click();

But I cannot use the window.hrefmethod, since it replaces the current page contents with the file you're trying to download.

但是我不能使用该window.href方法,因为它会用您尝试下载的文件替换当前页面内容。

Instead I want to open the download in new window/tab. How is this possible?

相反,我想在新窗口/选项卡中打开下载。这怎么可能?

回答by Randy the Dev

Use an invisible <iframe>:

使用隐形<iframe>

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
    document.getElementById('my_iframe').src = url;
};
</script>

To force the browser to download a file it would otherwise be capable of rendering (such as HTML or text files), you need the server to set the file's MIME Typeto a nonsensical value, such as application/x-please-download-meor alternatively application/octet-stream, which is used for arbitrary binary data.

要强制浏览器下载原本可以呈现的文件(例如 HTML 或文本文件),您需要服务器将文件的MIME 类型设置为无意义的值,例如application/x-please-download-meapplication/octet-stream,该值用于任意二进制数据。

If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its targetattribute set to _blank.

如果您只想在新选项卡中打开它,唯一的方法是让用户单击其target属性设置为的链接_blank

In jQuery:

在 jQuery 中:

$('a#someID').attr({target: '_blank', 
                    href  : 'http://localhost/directory/file.pdf'});

Whenever that link is clicked, it will download the file in a new tab/window.

每当单击该链接时,它都会在新选项卡/窗口中下载文件。

回答by John Culviner

2019 modern browsers update

2019 现代浏览器更新

This is the approach I'd now recommend with a few caveats:

这是我现在推荐的方法,但有一些注意事项:

  • A relatively modern browser is required
  • If the file is expected to be very largeyou should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.
  • 需要一个相对现代的浏览器
  • 如果预计文件非常大,您可能应该执行类似于原始方法(iframe 和 cookie)的操作,因为以下某些操作可能消耗的系统内存至少与正在下载的文件和/或其他有趣的 CPU 一样大副作用。

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(resp => resp.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    // the filename you want
    a.download = 'todo-1.json';
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    alert('your file has downloaded!'); // or you know, something with better UX...
  })
  .catch(() => alert('oh no!'));

2012 original jQuery/iframe/cookie based approach

2012 原始的基于 jQuery/iframe/cookie 的方法

I have created the jQuery File Download plugin(Demo) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:

我创建了jQuery 文件下载插件( Demo) ( GitHub),它也可以帮助解决您的情况。它与 iframe 的工作方式非常相似,但有一些很酷的功能,我发现这些功能非常方便:

  • Very easy to setup with nice visuals (jQuery UI Dialog, but not required), everything is tested too

  • User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications

  • successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation

  • In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demofor an example of this. Hope this helps someone!

  • 非常容易设置,具有漂亮的视觉效果(jQuery UI 对话框,但不是必需的),一切都经过测试

  • 用户永远不会离开他们启动文件下载的同一页面。此功能对于现代 Web 应用程序变得至关重要

  • successCallback 和 failCallback 函数允许您明确说明用户在任一情况下看到的内容

  • 结合 jQuery UI,开发人员可以轻松地向用户显示一个模式,告诉用户正在下载文件,在下载开始后解除模式,甚至以友好的方式通知用户发生了错误。有关此示例,请参阅演示。希望这可以帮助某人!

Here is a simple use case demo using the plugin sourcewith promises. The demo pageincludes many other, 'better UX' examples as well.

这是一个使用带有 promise的插件的简单用例演示。该演示页包含了许多其他“更好的UX”的例子也是如此。

$.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });

回答by Imagine Breaker

function downloadURI(uri, name) 
{
    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.click();
}

Check if your target browser(s) will run the above snippet smoothly:
http://caniuse.com/#feat=download

检查您的目标浏览器是否会顺利运行上述代码段:http:
//caniuse.com/#feat=download

回答by Helpful 13 Year Old

I'm surprised not a lot of people know about the download attribute for a elements. Please help spread the word about it! You can have a hidden html link, and fake a click on it. If the html link has the download attribute it downloads the file, not views it, no matter what. Here's the code. It will download a cat picture if it can find it.

我很惊讶没有多少人知道元素的下载属性。请帮忙宣传一下!你可以有一个隐藏的 html 链接,并假装点击它。如果 html 链接具有下载属性,它会下载文件,而不是查看它,无论如何。这是代码。如果它可以找到它,它将下载一张猫图片。

document.getElementById('download').click();
<a href="https://docs.google.com/uc?id=0B0jH18Lft7ypSmRjdWg1c082Y2M" download id="download" hidden></a>

Note: This is not supported on all browsers: http://www.w3schools.com/tags/att_a_download.asp

注意:并非所有浏览器都支持此功能:http: //www.w3schools.com/tags/att_a_download.asp

回答by Laura Chesches

I recommend using the downloadattributefor download instead of jQuery:

我建议使用download属性进行下载,而不是jQuery的:

<a href="your_link" download> file_name </a>

This will download your file, without opening it.

这将下载您的文件,而无需打开它。

回答by corbacho

If you are already using jQuery, you could take adventage of it to produce a smaller snippet
A jQuery version of Andrew's answer:

如果你已经在使用 jQuery,你可以利用它来生成一个更小的片段
安德鲁的答案的 jQuery 版本:

var $idown;  // Keep it outside of the function, so it's initialized once.
downloadURL : function(url) {
  if ($idown) {
    $idown.attr('src',url);
  } else {
    $idown = $('<iframe>', { id:'idown', src:url }).hide().appendTo('body');
  }
},
//... How to use it:
downloadURL('http://whatever.com/file.pdf');

回答by EL missaoui habib

Works on Chrome, Firefox and IE8 and above.

适用于 Chrome、Firefox 和 IE8 及更高版本。

var link=document.createElement('a');
document.body.appendChild(link);
link.href=url ;
link.click();

回答by Aaron Lelevier

Simple example using an iframe

使用一个简单的例子 iframe

function downloadURL(url) {
    var hiddenIFrameID = 'hiddenDownloader',
        iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;
};

Then just call the function wherever you want:

然后只需在您想要的任何地方调用该函数:

downloadURL('path/to/my/file');

downloadURL('path/to/my/file');

回答by Rohit Parte

This could be helpful if you are not require to navigate another page. This is base javascript function, so can be used in any platform where backend is in Javascript

如果您不需要导航另一个页面,这可能会有所帮助。这是基本的 javascript 函数,因此可以在后端为 Javascript 的任何平台中使用

window.location.assign('any url or file path')

回答by rakaloof

Only seven years later here comes a one line jQuery solution using a form instead of an iframe or link:

仅仅七年后,这里出现了一个使用表单而不是 iframe 或链接的单行 jQuery 解决方案:

$('<form></form>')
     .attr('action', filePath)
     .appendTo('body').submit().remove();

I've tested this in

我已经测试过这个

  • Chrome 55
  • Firefox 50
  • Edge IE8-10
  • iOS 10 (Safari/Chrome)
  • Android Chrome
  • 铬 55
  • 火狐 50
  • 边缘IE8-10
  • iOS 10 (Safari/Chrome)
  • 安卓浏览器

If anyone knows of any downsides with this solution I'd be very happy to hear about them.

如果有人知道这个解决方案的任何缺点,我会很高兴听到他们的消息。



Full demo:

完整演示:

<html>
<head><script src="https://code.jquery.com/jquery-1.11.3.js"></script></head>
<body>
<script>
    var filePath = window.prompt("Enter a file URL","http://jqueryui.com/resources/download/jquery-ui-1.12.1.zip");
    $('<form></form>').attr('action', filePath).appendTo('body').submit().remove();
</script>
</body>
</html>