Java 使用 JSP 下载文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4005873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using JSP to download a file
提问by tom man
I am currently trying to use JSP to build some small litle apps and have not got stuck on something, downloading files from a webserver. I just cant seem to work out how I should go about this task.
我目前正在尝试使用 JSP 来构建一些小的应用程序并且没有卡在某个东西上,从网络服务器下载文件。我似乎无法弄清楚我应该如何完成这项任务。
Are there any JSP developers here who know to go about this and could point me in the right direction?
这里是否有任何 JSP 开发人员知道如何解决这个问题并且可以为我指明正确的方向?
回答by BalusC
If the resource is static, just put it in the public webcontent (there where your JSP/HTML/CSS/JS/etc files also are) and include a link to it in your JSP.
如果资源是静态的,只需将它放在公共网页内容中(您的 JSP/HTML/CSS/JS/etc 文件也在那里)并在您的 JSP 中包含一个指向它的链接。
<a href="file.ext">download</a>
The servletcontainer will worry about setting the right HTTP response headers.
servletcontainer 会担心设置正确的 HTTP 响应头。
If the resource is dynamic, create a servlet which obtains an InputStream
of the content somehow (new FileInputStream
, resultSet.getBinaryStream()
, etc..etc..) and writes it to the OutputStream
of the response along at least the Content-Type
and Content-Disposition
response headers. Finally just link to that servlet in your JSP.
如果资源是动态的,则创建一个 servlet,它InputStream
以某种方式获取内容(new FileInputStream
、resultSet.getBinaryStream()
等.. 等)并将其OutputStream
至少沿着Content-Type
和Content-Disposition
响应标头写入响应的 。最后只需链接到您的 JSP 中的那个 servlet。
<a href="fileservlet/file.ext">download</a>
You can find a basic example in this article.
您可以在本文中找到一个基本示例。
The Content-Type
header informs the client about the content type of the file so that it knows what application it should use to open it. The Content-Disposition
header informs the client what to do with it, displaying it inline or saving as attachment.
该Content-Type
头通知有关内容类型的文件,以便它知道它应该使用什么应用程序来打开它的客户端。该Content-Disposition
头通知客户端做什么用的呢,内联显示它或者保存为附件。