如何Servlet中添加一个ServletOutputStream,用于向客户端返回文件内容。
时间: 2024-05-05 14:17:35 浏览: 97
servlet导出文件
可以通过在Servlet中创建一个ServletOutputStream对象,然后使用该对象将文件内容输出到客户端。常见的方法是使用response.setContentType()设置响应类型为"application/octet-stream",并使用response.setHeader()方法设置Content-Disposition为"attachment;filename=文件名",以便浏览器能够正确地处理文件。具体实现可参考以下代码:
```java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取要下载的文件名
String fileName = "test.txt";
// 设置响应类型为"application/octet-stream"
response.setContentType("application/octet-stream");
// 设置Content-Disposition为"attachment;filename=文件名"
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// 创建ServletOutputStream对象
ServletOutputStream out = response.getOutputStream();
// 读取文件内容并输出到ServletOutputStream对象
FileInputStream in = null;
try {
File file = new File(fileName);
in = new FileInputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.flush();
out.close();
}
}
}
```
阅读全文