javascript 任何干净的方式来下载文件,如 html5 下载属性

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

any clean ways to download files like html5 download attribute

javascriptjqueryhtml

提问by boburShox

I am fully aware that there are many debates(and solutions) out there in terms of downloading files in javascript/jQuery, such as iFrame, jQueryPlugin. However, I am more interested in a kind of built-in facilities like downloadattribute of <a>in HTML5. The problem is that it supports a couple of browsers:

我完全意识到在 javascript/jQuery 中下载文件方面存在许多争论(和解决方案),例如iFrame, jQueryPlugin. 然而,我更感兴趣的是一种内置的工具,比如HTML5 中的download属性<a>。问题是它支持几个浏览器

enter image description here

在此处输入图片说明

That is how I want to download files, without creating frames or using any plugins. The questions is are there any other cross browser built-in(say, easier or cleaner) ways to do it?

这就是我想要下载文件的方式,而无需创建框架或使用任何插件。问题是有没有其他跨浏览器内置(比如,更简单或更干净)的方法来做到这一点?

  • Internet Explorer 8+
  • Firefox 19+
  • Chrome 17+
  • Safari 5.1.9+
  • Opera 12.1
  • 浏览器 8+
  • 火狐 19+
  • 铬 17+
  • Safari 5.1.9+
  • 歌剧 12.1

回答by tsauerwein

You might want to try FileSaver.jswhich has support for all modern browsers.

您可能想尝试支持所有现代浏览器的FileSaver.js

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

回答by Marius

There is Downloadify, which generates and force downloads files with Flash. There's also a demoavailable.

Downloadify,它使用 Flash 生成并强制下载文件。还有一个演示可用。

Or you could download the file using XHttpRequest ($.get in jQuery) and use data URIs.

或者您可以使用 XHttpRequest(jQuery 中的 $.get)下载文件并使用数据 URIs