3

I have a java script file in which a variable has some string like:

var xw = 'Some content';

I want to download this string as a file. How to do this in JQuery/javascript? I don't want to send any request on server using AJAX. Is there any way to download in purely JQuery/javascript ?

5
  • Check this post. stackoverflow.com/questions/1296085/download-file-using-jquery Commented Oct 12, 2012 at 11:51
  • It works only when i have a file already created. But i don't have such type of any file. Commented Oct 12, 2012 at 11:54
  • Why can't you use a server side language or ajax? Commented Oct 12, 2012 at 11:56
  • This is a sample demo service. We are not using java and any other server side programming. This is normal HTML project. Commented Oct 12, 2012 at 12:09
  • Is there anyway to change the download file name? Right now it just shows as download?! Commented Nov 20, 2013 at 1:05

2 Answers 2

8
<a href="data:application/octet-stream;charset=utf-8;base64,U29tZSBjb250ZW50">Download "Some content" as a text file</a>

http://jsfiddle.net/5tJ5p/

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

9 Comments

How it is working? Do we need to encrypt data? Please can you explain it?
Yes, you need to encode data. In base64 in this case. Basically "U29tZSBjb250ZW50" is a base64 representation of "Some content" string. You can read more about this approach at developer.mozilla.org/en-US/docs/data_URIs or en.wikipedia.org/wiki/Data_URI_scheme. Please, consider browser adoption.
You can encode a string as base64 in JavaScript using btoa() function. For example: alert(btoa("Some content"));​
You can specify a download attribute on <a> tag, see jsfiddle.net/5tJ5p/1, but again you need to check details about adoption. You can also take a look at Blob and File API that provides another way to achieve the same objective. See html5-demos.appspot.com/static/a.download.html as an example.
If i want to download using window.location.href=URL then how to use download attribute to change name of file?
|
2

You're looking for Downloadify.

4 Comments

Not sure if that's what he wants. But then again, the question is horribly vague...
Not really a pure javascript/jquery solution, but I use a similar hack to onclick copy to the clip board.
I think it's the best he's going to find.
As much as I hate to upvote something that requires Flash, there doesn't seem to be a better cross browser solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.