简称Response类
常见应用
- 向浏览器输出消息
- 下载文件
- 要获取下载文件的路径
- 下载文件的名称
- 设置想办法让浏览器能够支持下载我们需要的东西
- 获取下载文件的输入流
- 创建缓冲区
- 获取OutputStream对象
- 将FileOutputStream流写入到debuffer缓冲区
- 使用OutputStream将缓冲区的数据输出到客户端!
package com.yin; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; public class servlet1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //要获取下载文件的路径 //String realPath=this.getServletContext().getRealPath("/1.png"); String realPath="E:\\code\\maven0\\response1\\src\\main\\resources\\1.png"; System.out.println("下载文件的路径:"+realPath); //下载文件的名称 String filename=realPath.substring(realPath.lastIndexOf("\\")+1); //设置想办法让浏览器能够支持下载我们需要的东西 //resp.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(filename,"utf-8"));//可解决中文名乱码 resp.setHeader("Content-Disposition", "attachment; filename="+filename); //获取下载文件的输入流 FileInputStream in= new FileInputStream(realPath); //创建缓冲区 int len=0; byte[] buffer=new byte[1024]; //获取OutputStream对象 ServletOutputStream out =resp.getOutputStream(); //将FileOutputStream流写入到buffer缓冲区//使用OutputStream将缓冲区的数据输出到客户端! while( (len=in.read(buffer))>0) out.write(buffer,0,len); in.close(); out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } }
标签:文件,realPath,resp,HttpServletResponse,缓冲区,import,下载 From: https://www.cnblogs.com/insoon/p/17047874.html