Java--文件下载

@WebServlet("/download")
public class Download extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建字节输入流读取对应的文件
        String realPath = getServletContext().getRealPath("/img/1.jpg");
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath));

        //2.设置响应消息头支持的类型
        response.setHeader("Content-Type","application/octet-stream");

        //3.设置响应头以下载的方式打开附件
        response.setHeader("Content-Disposition","attachment;filename=2.jpg");

        //4.通过响应对象获取字节输出流对象
        ServletOutputStream os = response.getOutputStream();

        byte[] by = new byte[1024];
        int len;
        while (-1 != (len = bis.read(by))){
            os.write(by,0,len);
        }
        bis.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
posted @ 2020-08-14 15:43  德华。  阅读(177)  评论(0编辑  收藏  举报