我如何生成一个文件并提供它以简单的javascript下载? [英] How can i generate a file and offer it for download in plain javascript?

查看:165
本文介绍了我如何生成一个文件并提供它以简单的javascript下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在javascript动态地生成一个文本文件,然后提供这个下载。目前,我可以通过以下解决方案之一获得此程度的工作:

I would like to generate a text file in the javascript dynamicly, then offer this for download. Currently I can get this working to a degree with either of the following solutions:

content = "abc123";
document.location = "data:text/octet-stream," + encodeURIComponent(content);

content = "abc123";    
var bb = new BlobBuilder();
bb.append(content);
var blob = bb.getBlob();
blob = blob.slice(0, blob.size, 'text/octet-stream');
var fr = new FileReader(); 
fr.onload = function() {document.location = this.result;}
fr.readAsDataURL(blob);

但是,当出现下载框时,这两种解决方案只能提供默认的下载在保存为对话框中。

However, Both of these solutions, when the download box appears, will only offer a default filename of 'download' in the save as dialogue.

我的问题基本上是如何将其更改为一个特定的文件名,例如'readme.txt'或'scene.obj'

My question is basically, how can I change this to a specific filename for example 'readme.txt' or 'scene.obj'

另请注意,数据类型以前是text / plain,但是如果使用这种方式,则文档将切换到新的文本文档,而不是提供下载(作为文本/八位字节流似乎做)。

Also note the data type was previously 'text/plain' however if this is used, the document switches to the new text document instead of offering it for download (as text/octet-stream seems to do).

我不想要一个flash解决方案,只有javascript / html5的建议。

I do not want a flash solution, javascript/html5 only suggestions please.

干杯,Josh

推荐答案

为此,您必须使用 FileSaver
现在,这只是一个草稿,根据邮件列表答案它还没有在浏览器中实现。

For that, you will have to use FileSaver from FileAPI: Writer specification. For now, it's only a draft, and according to mailing list answer it isn't yet implemented in browsers.

您可以在铬问题获取有关实施进度的最新信息

You can watch for example on a chromium issue to get up-to-date information about the implementation progress

UPD 02.08.2013:我已经发现了一个项目,提供FileSaver界面使用整洁的技巧

UPD 02.08.2013: I have since found a project that provides FileSaver interface using neat tricks

这篇关于我如何生成一个文件并提供它以简单的javascript下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆