views:

30

answers:

2

I want to let the user download the current content of a textarea into a text file on their computer. In the past I would create an iframe pointing to a URL with the data, which would trigger a file download dialog. However this time the data is client side.

So, is it possible to let the user download data without sending it server side?

+2  A: 

If it does not need to work in "old browsers" like IE, you could open a new window with the location 'data:text/plain,' + yourTextarea.value. The user can then save that file using the File/Page menu or Ctrl+S.

janmoesen
+2  A: 

is it possible to let the user download data without sending it server side?

In the general case no.

It is possible with a data: URL, as in janmoesen's answer (although you should be URL-encoding the value to include in the URL, or you may face corruption when a %nn sequence appears in the data).

However, this becomes impractical for very long data, and it's not available in old browsers or IE. (IE8 allows short data URLs to be used for images, but not direct navigation.) So whilst you can include a data-URL method to enhance the process on browsers that support it, you will still need a fallback solution of sending a formful of the data to the server side and having it spit back a file in response.

(For security reasons, this should only be allowed in a POST request, and the server should include Content-Disposition: attachment in the response. A content-echo script can give you cross-site-scripting problems otherwise.)

bobince