强制使用JavaScript中的FileWriter创建blob下载 [英] Force download for blob created with FileWriter in JavaScript

查看:82
本文介绍了强制使用JavaScript中的FileWriter创建blob下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML5引入了FileWriter类。通过这个课程,你可以制作Blob。 (文件是Blob的扩展名。)使用JavaScript,您可以创建一个Blob,例如使用dataURL显示它。



示例:

  var bb = new BlobBuilder(); 
bb.append('some text')
var blob = bb.getBlob('text / plain');

var fr = new FileReader();
fr.onload = function(e){
document.location = this.result; // voila the dataURL
}
fr.readAsDataURL(blob);

但这还不够好:)我想要下载新创建的文本文件。不是在同一个窗口或单独的窗口中打开。



有没有办法?必须有。如何?



(讨论已存在于 Google Chrome群组



更新

File API已经改变,因为规格已经改变了(或者什么!?)。 Webkit打破了与 BlobBuilder ,现在称为 WebKitBlobBuilder 的向后兼容性。 在jsFiddle上有不同的示例



更新

创建Blob现在再次有所不同(不再 append()):

  blob = new Blob(['some text'],{type:'text / plain'}); 


解决方案

下载代码与Blob对象结合使用技巧(至少在最新的Chrome版本中)。请参阅此小提琴

  var blob = new Blob(['blaaaaat'],{type:'text / plain'}); 
$('a')。attr(href,window.URL.createObjectURL(blob));
$('a')。attr(download,woeii.txt);



不过,有关在Firefox中执行下载属性的讨论在此处可用



编辑:截至2013年10月3日,最新的Firefox版本现在支持下载属性


HTML5 introduces the FileWriter class. With this class you can make Blobs. (A File is an extension of a Blob.) With JavaScript you can make a Blob and for instance show it using the dataURL.

Example:

var bb = new BlobBuilder();
bb.append('some text')
var blob = bb.getBlob('text/plain');

var fr = new FileReader();
fr.onload = function(e) {
 document.location = this.result; // voila the dataURL
}
fr.readAsDataURL(blob);

But that's not good enough :) I want the newly created (text) file to be downloaded. Not opened in the same or a separate window.

Is there a way? There must be. How?

(The discussion already exists in the Google Chrome group)

UPDATE
The File API has changed, because the specs have changed (or something!?). Webkit broke backward compatibility with BlobBuilder, now called WebKitBlobBuilder. Same example differently on jsFiddle

UPDATE
Creating Blobs now works differently again (no more append()):

blob = new Blob(['some text'], {type: 'text/plain'});

解决方案

The download tag in combination with the Blob object does the trick (at least in the latest chrome versions). See this fiddle:

var blob = new Blob(['blaaaaat'], {type: 'text/plain'});
$('a').attr("href", window.URL.createObjectURL(blob));
$('a').attr("download", "woeii.txt");

F̶i̶r̶e̶f̶o̶x̶ ̶d̶o̶e̶s̶n̶'̶t̶ ̶s̶u̶p̶p̶o̶r̶t̶ ̶t̶h̶e̶ ̶d̶o̶w̶n̶l̶o̶a̶d̶ ̶a̶t̶t̶r̶i̶b̶u̶t̶e̶ though (it does support the Blob object). Discussions about implementation of the download attribute in Firefox are available here:

Edit: The download attribute is now supported by the latest firefox versions as of 10/3/2013

这篇关于强制使用JavaScript中的FileWriter创建blob下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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