---
title: "spring mvc 将图片文件以流的方式写入到jsp页面"
author: "hae"
date: "2015-01-12T17:07:18Z"
tags: []
categories: ["开源软件"]
slug: "spring-mvc-jsp"
draft: false
lastmod: "2015-01-12T17:08:18Z"
id: 2175133
url: "https://hae.iteye.com/blog/2175133"
---

spring mvc不像struts2：

Xml代码  [![收藏代码](http://sagewsg.iteye.com/images/icon_star.png)]()

1. &lt;action name="TwoDimensionalCodeAction" class="com.wsg.action.TwoDimensionalCodeAction"&gt;
2. &lt;result type="stream"&gt;
3. &lt;param name="inputName"&gt;inputStream&lt;/param&gt;
4. &lt;/result&gt;
5. &lt;result name="testForm"&gt;/form\_success.jsp&lt;/result&gt;
6. &lt;/action&gt;

 直接设置结果既可实现跳转，显示页面。

 

在spring mvc的action中需要设置response,具体如下：

```
@RequestMapping(value="/getpic", method = RequestMethod.GET)
public String getpic(Model model, HttpServletResponse response) throws IOException {
	response.setContentType("image/jpeg"); // 设置返回内容格式
	File file = new File("d:/a.jpg");       //括号里参数为文件图片路径
	if(file.exists()){   /如果文件存在
		InputStream in = new FileInputStream("d:/a.jpg");   //用该文件创建一个输入流
		OutputStream os = response.getOutputStream();  //创建输出流
		byte[] b = new byte[1024];  
		while( in.read(b)!= -1){ 
		os.write(b);     
		}
		in.close(); 
		os.flush();
		os.close();
	}
	return null;
}
```

 

这里选择相应的跳转，return null即可！

 

如果这样在把二进制流发送到页面时，response的流会出现一个问题:

 

Java代码  [![收藏代码](http://sagewsg.iteye.com/images/icon_star.png)]()

1. threw exception \[java.lang.IllegalStateException: getOutputStream() has already been called for this response] with root cause
2. java.lang.IllegalStateException: getOutputStream() has already been called for this response

 

这个时候页面加上以下代码即可解决

Java代码  [![收藏代码](http://sagewsg.iteye.com/images/icon_star.png)]()

1. &lt;%
2. out.clear();
3. out=pageContext.pushBody();
4. %&gt;