问题
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