make document available for download through java/servlet

丶灬走出姿态 提交于 2019-12-01 01:40:57

You need to add following headers in your servlet to make it a downloadable content so browsers don't try to display it,

String value = "attachment;filename=\"" + URLEncoder.encode(filename, "UTF-8") +'"';
response.setHeader("Content-Disposition", value);
response.setHeader("Content-Transfer-Encoding", "binary");

The filename is proposed filename and user can change it.

I wonder if your link html doesn't have something like:

<a href="/foo" **target="_blank"** ....>download</href>

Otherwise, it should work as you want.

This is a bug in IE which depends on several things, the content type is one of them. We had the same problem a few years ago but I don't remember the correct solution anymore, only that we struggled with this for quite some time. Try this:

  • Use the correct content type (application/pdf)
  • If that doesn't work, use a wrong file type (like application/octet-stream) which should tell IE to leave the file alone. You may have problems with the file extension, though.
  • Send or don't send the correct file size
  • Check which chunking mode you're using.

One of these things made IE behave. Good luck.

You need to remove target="_blank" from your <a> element.

Edit: as per your comments: you need to set Content-Disposition header to attachment. You can find here examples of a simple fileservlet and an advanced fileservlet to get some insights.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!