httpservletresponse 发送二进制文件
时间: 2023-08-24 20:06:10 浏览: 72
要发送二进制文件,可以使用以下代码:
```java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置响应内容类型
response.setContentType("application/octet-stream");
// 读取二进制文件
File file = new File("your_file_path_here");
FileInputStream fis = new FileInputStream(file);
// 设置响应头
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
// 写出文件
OutputStream os = response.getOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
os.write(buffer, 0, len);
}
os.close();
fis.close();
}
```
在上面的代码中,我们首先设置了响应内容类型为 `application/octet-stream`,这是二进制文件的 MIME 类型。接着我们读取了文件,将响应头中的 `Content-Disposition` 字段设置为 `attachment`,这样浏览器就会提示用户下载该文件,而不是在浏览器窗口中打开它。最后,我们将文件内容写入到 `HttpServletResponse` 的输出流中,以便将其发送给客户端。
相关推荐
![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)