httpservletresponse 发送二进制文件
时间: 2023-08-24 15:07:13 浏览: 99
要想发送二进制文件,可以使用以下代码:
```java
// 设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=filename.ext");
// 获取文件数据并写入响应流
InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
outputStream.close();
inputStream.close();
```
其中,`response.setContentType("application/octet-stream")` 设置响应类型为二进制流,`response.setHeader("Content-Disposition", "attachment;filename=filename.ext")` 设置响应头,提示浏览器下载文件。`inputStream` 为获取文件数据的输入流,`outputStream` 为响应输出流,将文件数据写入响应流中即可。
阅读全文