使用servlet从服务器下载Excel文件

5
我在服务器端有一个Excel文件,我如何使用servlet在客户端浏览器上显示它?
提前致谢。
1个回答

25
简而言之,通过某种方式(如FileInputStream),获取一个输入流,然后按照Java IO的方式将其写入响应的输出流中。这就是全部内容。您只需要确保设置正确的响应头,以便浏览器知道如何处理它。 Content-Type头文件会告诉Web浏览器它是什么类型的文件,以便浏览器知道使用哪个应用程序来打开它。
以下是一个示例:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String filename = URLDecoder.decode(request.getPathInfo(), "UTF-8");
    File file = new File("/path/to/files", filename);

    response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
    response.setHeader("Content-Length", file.length());
    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        input = new BufferedInputStream(new FileInputStream(file));
        output = new BufferedOutputStream(response.getOutputStream());

        byte[] buffer = new byte[8192];
        for (int length = 0; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }
    } finally {
        if (output != null) try { output.close(); } catch (IOException ignore) {}
        if (input != null) try { input.close(); } catch (IOException ignore) {}
    }
}

将此servlet映射到web.xml中的/files/* url-pattern,以使您可以通过http://example.com/contextname/files/filename.xls获取Excel文件。

如果实际上是xlsx文件(平均servlet容器默认不支持),则ServletContext#getMimeType()会返回application/octet-stream而不是所需的xlsx内容类型,则还需要在web.xml中添加以下条目:

<mime-mapping>
    <extension>xlsx</extension>
    <mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type>
</mime-mapping>

如果您需要一个更高级的文件servlet示例,您可能会发现这篇文章也很有用,它还支持在每个下载下恢复。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接