Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  72] [ 3]  / answers: 1 / hits: 19724  / 11 Years ago, tue, march 12, 2013, 12:00:00

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!


More From » file

 Answers
8

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/


[#79658] Monday, March 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nadiaa

Total Points: 572
Total Questions: 113
Total Answers: 113

Location: Mauritania
Member since Sun, Oct 17, 2021
3 Years ago
;