如何用JSP提供文件? [英] How to serve a file with JSP?

查看:131
本文介绍了如何用JSP提供文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能听起来很愚蠢,但却是现实生活中的情况:(

This may sound totally stupid, but is a case of real life :(

我能够显示带有虚拟链接名称的HTML表格。

I'm able to display a HTML table with a "virtual" link name.

这样的事情:

Xyz description   <a href="docId=123">document.doc</a>

Xyz description  <a href="docId=456">documentB.doc</a>

Xyz description  <a href="docId=798">documentC.doc</a>

此doc ID表示数据库中的id(对于这些docs存储在blob中作为byte [])

This doc id represents an id in the database ( for these docs are stored in a blob as byte[] )

无论如何。我能够获得该id,查询数据库并检索byte [](甚至将其存储在tmp文件中)

Anyway. I'm able to get that id, query the database and retrieve the byte[] ( and even store it in a tmp file )

我无法弄清楚怎么做,是,当用户点击链接(并在我执行数据库检索后)将[]字节[]发送给用户。

What I can't figure out how to do, is, that when the user click on the link ( and after I perform the db retrieval ) "serve" the byte[] to the user.

现在最糟糕的部分,是什么让我这里问这个问题,我只需要用JSP做这个(没有servlet )没有第三方图书馆(只是......不要问我为什么我也讨厌它)

Now the very worst part, and what makes me ask this question here is, I need to do this with JSP only ( no servlet ) and without 3rd party libraries ( just... don't ask me why I hate it too )

所以。如何在jsp中提供存储在服务器文件系统中的字节数组的二进制内容

So. How do I serve in a jsp the binary content of a byte array stored in the server file system

我的第一位客人是:

<%
InputStream read // read the file form the fle system 
response.getOutputStream().write( theBytesReader );
%>

我是否接近解决方案?

Am I close to the solution?

这对客户端是否有效,就像他真的在服务器中点击了真实文件一样?

Would this work to the client as if he had clicked really in the server for a real file?

提前致谢。

推荐答案

简而言之,只需在JSP中编写相同的代码,就像在 Servlet类。你几乎可以将它复制。只确保您将任何模板文本写入流中,这包括scriptlet外部的换行符和空格。否则它也会被写入二进制文件并破坏它。

To the point, just write the same code in JSP as you would do in a Servlet class. You can practically copypaste it. Only ensure that you are not writinig any template text to the stream, this includes linebreaks and whitespace outside the scriptlets. Otherwise it would get written to the binary file as well and corrupt it.

如果你有多个scriptlet块,那么你需要安排它们,以便在结尾%> 一个scriptlet和下一个scriptlet的起始<%。因此,例如

If you have multiple scriptlet blocks, then you need to arrange them so that there's no linebreak between the ending %> of a scriptlet and the starting <% of the next scriptlet. Thus, e.g.

<%@page import="java.io.InputStream" %><%
    //...
%>

而不是

<%@page import="java.io.InputStream" %>
<%
    //...
%>

这篇关于如何用JSP提供文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆