简体   繁体   中英

How to change the file name during the download process

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 ?

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. Eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM