重新学javaweb---文件下载

1.

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        resp.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("图片啦啦啦.jpg","utf-8"));//响应头中不能包含中文 +encode编码时浏览器只认识u8
        resp.setContentType("image/jpeg");//MIME类型
        //resp.setContentType( this.getServletContext().getMimeType(filename));//MIME类型 根据文件名的后缀 自己判断MIME格式
        FileInputStream inputStream = new FileInputStream(this
                .getServletContext().getRealPath("1.png"));
        OutputStream os = resp.getOutputStream();
        byte[] bs = new byte[1024];
        int i = 0;
        while ((i = inputStream.read(bs)) != -1) {
            os.write(bs, 0, i);
        }
        inputStream.close();
          //输出 out 不需要我们手动关闭
    }

你可能感兴趣的:(download)