Skip to content Skip to sidebar Skip to footer

Force Download For Blob Created With Filewriter In Javascript

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 th

Solution 1:

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


Solution 2:

Here is a pure Javascript solution for creating a text blob and download as text file

var fileContent = 'This is sample text file';
var fileName = 'sampleFile.txt';

const blob = new Blob([fileContent], { type: 'text/plain' });
const a = document.createElement('a');
a.setAttribute('download', fileName);
a.setAttribute('href', window.URL.createObjectURL(blob));
a.click(); // EXECUTING CLICK EVENT WILL AUTO-DOWNLOAD THE FILE

Post a Comment for "Force Download For Blob Created With Filewriter In Javascript"