tomcat在代码中实现将文件响应给客户端?

2025-01-08 01:24:26
推荐回答(1个)
回答1:

protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("application/jar");
        ServletContext ctx = getServletContext();
        InputStream inputStream = ctx
                .getResourceAsStream("/resources/bookCode.jar");
        int read = 0;
        byte[] bytes = new byte[1024];
        OutputStream oStream = response.getOutputStream();
        while ((read = inputStream.read(bytes)) != -1) {
            oStream.write(bytes, 0, read);
        }
        oStream.flush();
        oStream.close();
    }

将代码中这个路径:"/resources/bookCode.jar" 改为你的文件路径,注意区分这里的绝对路径和相对路径。有疑惑再问。