Servlet-Response响应字节数据
Servlet-Response响应字节数据
使用:
- 通过Resonse对象获取字节输出流
ServletOutputStream outputStream = resp.getOutputStream();
- 写数据
outputStream.write(字节数据);
适合:图片/音视频/文件下载等“二进制语义”的响应(关联:HTTP响应报文 / Servlet-响应数据)。
常见响应头(按场景选)
- 浏览器直接展示(图片等):设置正确的
Content-Type - 触发下载:设置
Content-Disposition: attachment;filename=... - 大文件:分块写出,避免一次性读入内存
可以通过apache的commons-io工具类实现
- 导入坐标
- 使用
-IOUtils.copy(输入流, 输出流);
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.读取文件
FileInputStream fis = new FileInputStream("D://b.png");
// 2. 获取response字节输出流
ServletOutputStream os = resp.getOutputStream();
// 3. 完成流的copy
/*byte[] buff = new byte[1024];
int len = 0;
while ((len = fis.read(buff)) != -1){
os.write(buff, 0, len);
}*/
// apache提供的工具类实现字节数据的拷贝,需要在pom.xml添加commons-io坐标
IOUtils.copy(fis, os);
fis.close();
}
更贴近 Web 工程的读取方式
示例里用的是服务器本地绝对路径。实际项目中更常见的是从 Web 应用资源目录读取,例如用 ServletContext#getResourceAsStream(避免写死磁盘路径)。