Ranjan Sarma
Ranjan Sarma

Reputation: 1595

Ajax/Javascript - File Download

  1. Client (Request through XMLHttpRequest) -> Server.
  2. Server [Builds CSV and prints it on the output stream of response] -> Client.

Now step 3 should be-> Client's browser should show a download dialogue (save, open and cancel). Since the content type is plain text from the server, and the content disposition is not set, can we create a file using javascript and prompt the user to download?

I know this question is slight stupid. But there is no other option. I have to do it this way.

Changing in the server side script will make it a one minute task. But I have to do it in the client side. The responseText property of the XMLHttpRequest object will be plain text and I have to show download prompt for the text file.

Is this possible?

Upvotes: 0

Views: 1374

Answers (2)

Manak Kapoor
Manak Kapoor

Reputation: 982

Theoretically it could be possible, by using Data URI's

<a download = "yourfile.csv" href="data:application/octet-stream;charset=YOURCHARSET;base64,BASE64allthedata">Generate</a>

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Not that I'm aware of. But you could just use location.href (or a form, if POST data is needed) to request the server-side file. With the correct headers (Content-Disposition: attachment and I think there's another one) you can have the response be downloaded rather than displayed.

EDIT: Even better, use an iframe that's hidden. That way, you can still do a fancy "Loading, please wait" thing in the main page.

Upvotes: 1

Related Questions