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

use*_*012 4 servlets download

我在服务器端有一个Excel文件.如何使用servlet在客户端浏览器上显示它?

提前致谢.

Bal*_*usC 23

要点:InputStream以某种方式得到它(FileInputStream适合)并将其写入OutputStream通常的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) {}
    }
}
Run Code Online (Sandbox Code Playgroud)

将此servlet映射web.xml到一个url-pattern,/files/*以便您可以获取excel文件http://example.com/contextname/files/filename.xls.

如果它实际上是一个xlsx文件,默认情况下不会被普通的servletcontainer识别(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>
Run Code Online (Sandbox Code Playgroud)

对于文件servlet的更高级示例,您可能会发现本文也很有用,它也支持每个下载简历.