如何让浏览器直接下载后端返回的图片而不是打开
时间: 2024-03-08 21:49:07 浏览: 25
要实现浏览器直接下载后端返回的图片而不是打开,可以在服务器端设置响应头,将 Content-Disposition 属性设置为 attachment,这样浏览器就会提示用户下载文件而不是在浏览器中打开它。
以下是一个示例代码:
```java
@GetMapping("/downloadImage")
public void downloadImage(HttpServletResponse response) throws IOException {
// 从文件系统或其他位置获取你的图片资源
File file = new File("/path/to/your/image.jpg");
// 设置响应头
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=image.jpg");
// 从文件读取图片数据并写入响应流
InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
}
```
这个方法将会直接将图片数据写入响应流,并设置响应头的 Content-Disposition 属性为 attachment,浏览器将会提示用户下载这张图片而不是在线打开它。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)