Skip to content

Instantly share code, notes, and snippets.

@danallison
Created September 29, 2014 16:44
Show Gist options
  • Star 47 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save danallison/3ec9d5314788b337b682 to your computer and use it in GitHub Desktop.
Save danallison/3ec9d5314788b337b682 to your computer and use it in GitHub Desktop.
download string as text file
function downloadString(text, fileType, fileName) {
var blob = new Blob([text], { type: fileType });
var a = document.createElement('a');
a.download = fileName;
a.href = URL.createObjectURL(blob);
a.dataset.downloadurl = [fileType, a.download, a.href].join(':');
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(function() { URL.revokeObjectURL(a.href); }, 1500);
}
// downloadString("a,b,c\n1,2,3", "text/csv", "myCSV.csv")
@DCzajkowski
Copy link

Thanks!

Copy link

ghost commented Jul 13, 2019

This is absolutely incredible!!!
Thank you so much for making this!!!

@HeitorAugustoLN
Copy link

Does this work for raw pastebin texts?

@spamvictus
Copy link

This assumes that the file data is being written onto my drive faster than 1,5secs, amirite?

Copy link

ghost commented Jun 7, 2021

@spamvictus

This assumes that the file data is being written onto my drive faster than 1,5secs, amirite?

?

@danallison
Copy link
Author

I'm actually not sure what the timeout is for. I wrote this so long ago that I don't remember.

Looks like there's a more robust and actively maintained solution here: https://github.com/eligrey/FileSaver.js/blob/master/src/FileSaver.js

It also uses a timeout before revoking the url, set to 40 seconds.

Also, from that repo's README:

If you need to save really large files bigger than the blob's size limitation or don't have enough RAM, then have a look at the more advanced StreamSaver.js that can save data directly to the hard drive asynchronously with the power of the new streams API. That will have support for progress, cancelation and knowing when it's done writing

@spamvictus
Copy link

Wow ty, I will have a look at it

@daohodac
Copy link

Fantastic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment