且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

强制使用JavaScript中的FileWriter创建blob下载

更新时间:2023-12-03 20:35:52

下载代码与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