Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically create a client side file in Javascript that can be downloaded by the user? [duplicate]

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!

like image 538
ZenBalance Avatar asked Mar 12 '13 00:03

ZenBalance


People also ask

How do you make a file downloadable in JavaScript?

To receive our files URL, we use URL. createObjectURL() which receives our file object as a parameter. Then, specify the name the saved file should have by default with setting the download attribute of the link. Finally, we mount the link in the DOM, click it artificially, and remove it from the DOM.

Can client side script access the file system?

Client-side code is written using HTML, CSS, and JavaScript — it is run inside a web browser and has little or no access to the underlying operating system (including limited access to the file system).

Can JavaScript create a file?

Did you know you can create files using JavaScript right inside your browser and have users download them? You can create files with a proper name and mime type and it only takes a few lines of code.


1 Answers

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/

like image 119
Graham Robertson Avatar answered Oct 21 '22 01:10

Graham Robertson