Link to home
Start Free TrialLog in
Avatar of killdurst
killdurst

asked on

How to initiate the download dialog box?

On my JSP page I have a link that says "Download as text". When I click it, it will go to a servlet where a txt file will be created. The servlet would then redirect to this txt file. The problem is, when I click on the "Download as text" link, the file will be displayed on the browser itself. How do I change this so that when the link is clicked, the download dialog box will be displayed instead?
ASKER CERTIFIED SOLUTION
Avatar of Devario Johnson
Devario Johnson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of killdurst
killdurst

ASKER

I'm also looking into some of the HttpServletResponse methods. Below are what I came up with, but it's still not working. Are there any errors in the code?

String requestURL = "test.txt";
response.setContentType("text/html");
response.setHeader("Content-Disposition", "attachment;filename=test.txt");
response.sendRedirect(response.encodeRedirectURL(requestURL));

"response" is a HttpServletResponse object.
When you are serving the text file, add "Content-Disposition: attachment" header
Hi Ajay, I think we posted at around the same time. Is my post above yours what you are talking about? I've already added the header.
> response.sendRedirect(response.encodeRedirectURL(requestURL));

You should not redirect. You should server file from here (read from file and write to servlet)
I sorta knew that that line was wrong, but I don't know what I should write. What should I write?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The choice of whether to download or view a file is completely controlled by the user's browser settings.  Essentially ALL browsers will simply VIEW a TXT file.  Even if it is a TEXT file, give it a ZIP extension, or zip it, and then almost all browsers will initiate the download save-as dialog box.  The first reply said this TOO.