怎么使用HttpServletResponse返回输出流
时间: 2024-06-13 07:05:46 浏览: 16
以下是使用HttpServletResponse返回输出流的示例代码:
```java
@RequestMapping("/download")
public void download(HttpServletResponse response) throws IOException {
// 设置文件名和文件类型
response.setHeader("Content-Disposition", "attachment;filename=test.txt");
response.setContentType("application/octet-stream");
// 获取文件输入流
InputStream inputStream = new FileInputStream(new File("test.txt"));
// 获取输出流
OutputStream outputStream = response.getOutputStream();
// 缓冲区大小
byte[] buffer = new byte[1024];
int len;
// 将文件写入输出流
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
// 关闭输入流和输出流
inputStream.close();
outputStream.close();
}
```
在上述代码中,我们首先设置了文件名和文件类型,然后获取了文件输入流和输出流。接着,我们使用缓冲区将文件写入输出流,并在最后关闭输入流和输出流。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)