make document available for download through java/servlet

南笙酒味 提交于 2019-11-30 20:06:37

问题


I need to know if there is a way in java/servlet to make documents(doc,pdf) stored in database available for download to users in requested way(please see below),

for example there is a web page and the link for document in it

right now it is done this way: if the user clicks that link than a new blank window opens and there the download dialog box is shown and the user is able to download the document but that blank window stays open and the user have to close it manually

but wish to do it this way: If the User clicks that link than directly staying on that page a download dialog box should show up asking them to save the file

a servlet url handles the download of the document which is responsible for extracting the doc form database and makes available for download to users

thank you for your time and effort


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/1840703/make-document-available-for-download-through-java-servlet

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