7

I wanted to experiment creating a Javascript application that takes input from the user in a form and then generates a file based on the user's form input.

The file should then be downloadable by the user all without touching the server.

How do you create a file on the client side with JavaScript and where on the client side could it be stored so that it can be downloaded without being first created on the server?

Update: To be more specific as Graham answered, I was looking for way to create the file without necessarily touching the file system itself, but just creating a file object (a Blob) that could be downloaded by the user. Thanks Graham!

6
  • 2
    Is there a specific browser and browser-version that you're targeting? (I ask because I think you'll need to use the data: URL protocol for this, and not all browser-versions support it.) Commented Mar 12, 2013 at 0:02
  • You could always try to spray the heap :P Commented Mar 12, 2013 at 0:02
  • 2
    possible duplicate of Create a file in memory for user to download, not through server see also Javascript: Create and save file Commented Mar 12, 2013 at 0:03
  • Those links are very helpful. Flash is not a viable solution and the other thread's solution doesn't work well across browsers. I found this: html5rocks.com/en/tutorials/file/filesystem, but still not quite satisfying. Commented Mar 12, 2013 at 0:11
  • 1
    It's not just supported by Chrome actually and many browser implement the Filesystem API. And, actually, it's an official w3 specification so, yes, it is part of "HTML5". Commented Mar 12, 2013 at 3:55

1 Answer 1

18

One way to do this without having to use the filesystem is to create blobs. Let's say we have a bunch of data (in your case, from a form) and we wish to save it to a text "file". We could actually do something as follows:

var formBlob = new Blob([someStringVariable], { type: 'text/plain' }); 

From here, we could link a user to download this as an actual file like so:

someLink.href = window.URL.createObjectURL(formBlob); 

If we wanted this data to persist, we could serialize our blob as a base64 string and save it to localStorage or any other persistent type of storage. Converting blobs to base64 is a bit beyond the scope of this answer but you can find a good reference/library here: http://blog.danguer.com/2011/10/24/base64-binary-decoding-in-javascript/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.