(4) 练习 - 文件下载(防盗链,支持单页面多下载)

View

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print("图片1
"
); writer.print("图片2
"
); writer.print("图片3
"
); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }

DownLoadServlet

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String url = request.getHeader("referer");
        if (url == null || !url.startsWith("http://localhost/ServletDemo1")) {
            response.sendRedirect("/ServletDemo1/Error");
        }
        response.setContentType("text/html;charset=UTF-8");
        String filename = request.getParameter("filename");
        String newFilename = new String(filename.getBytes("iso-8859-1"),
                "utf-8");
        // 获取 项目下文件的 真实路径
        String path = this.getServletContext().getRealPath(
                "/" + newFilename + ".png");

        // 设置下载即可
        String fileUrlName = java.net.URLEncoder.encode(newFilename, "utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                + filename + "");
        InputStream inputStream = new FileInputStream(path);
        OutputStream outputStream = response.getOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buf)) > 0) {
            outputStream.write(buf, 0, len);
        }
        inputStream.close();
        outputStream.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

Error

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("休想盗链!");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

你可能感兴趣的:(Servlet,下载)