Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the file name during the download process

Tags:

java

jsp

I have a file named "MyFile.doc" on my server and a jsp in the same instance. There is a redirection in the jsp like : response.sendRedirect("MyFile.doc");. When a user comes to my jsp file, I want to give the file as "MyFile_XYZT.doc". In short, it should be downloaded with an ID created dynamically.

I've searched and found something about Content-Disposition method.

Any ideas ?

like image 743
anL Avatar asked Feb 14 '23 19:02

anL


1 Answers

I've searched and found something about Content-Disposition method.

Right, that's how you tell the browser what you'd like it to do with the response, including optionally giving a suggested filename for a download.

I don't think there's any one-liner here, though. You either need to configure your server to return MyFile.doc with the relevant Content-Disposition header or, if you want to control the name with code in your JSP, you'll have to send the response yourself using setHeader to set the Content-Disposition header. E.g.:

response.setHeader("Content-Disposition", "attachment; filename=\"MyFile_XYZT.doc\"");

...and then opening the file, reading its contents, and sending those in the response. It's not a lot of code (probably four or five lines), but it's not a one-liner.

like image 136
T.J. Crowder Avatar answered Feb 17 '23 10:02

T.J. Crowder