JAVA读取MongoDB中的二进制图片并显示在页面上

1:Jsp页面:

<td><img src="${ctx}/mongoImg/show"></td>

2:xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
        http://www.springframework.org/schema/data/mongo       
        http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd   
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<mongo:mongo host="${resource.db.host}" port="${resource.db.port}" />

	<mongo:db-factory id="mongoDbFactory" dbname="gate" mongo-ref="mongo" />

	<bean class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
		<constructor-arg ref="mongoDbFactory" />
		<constructor-arg ref="converter" />
	</bean>

	<mongo:mapping-converter id="converter"/>
</beans>

3:java后台代码

package com.crscic.igms.manager.web;

import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mongodb.gridfs.GridFSDBFile;

@Controller
@RequestMapping(value = "/mongoImg")
public class MongoImgController {
	
	@Autowired
	GridFsTemplate gridFsTemplate;
	
	@RequestMapping(value = "/show")
	public void show(HttpServletRequest req, HttpServletResponse resp){
		try {
			OutputStream out = resp.getOutputStream();
			resp.setContentType("image/png");
			List<GridFSDBFile> find = gridFsTemplate.find(null);
			GridFSDBFile gridFSDBFile = find.get(0);
			gridFSDBFile.writeTo(out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
在JAVA代码中,因为只是个例子而已,所以我使用的是gridFsTemplate.find(null);查询的全部图片,而且数据库中只有2条数据,我这里就把第一条数据查出来作为例子了。各位可以根据自己的业务需要,在页面传递参数进来,并且查询特定的数据。


 

猜你喜欢

转载自blog.csdn.net/u012138706/article/details/52180665