SSM+MongoDB存取图片
涉及到的主要技术框架是
SpringMVC
Spring
Mybatis
MongoDB
基础依赖搭建
SSM项目搭建和mongoDB的安装和运行就不再赘述,直接从接入mongoDB开始说起
加入spring-data-mongodb依赖
首先第一步是添加mongo的Spring依赖,我这边用的版本是1.6.2
<spring-data.version>1.6.2.RELEASE</spring-data.version>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring-data.version}</version>
</dependency>
新建一个spring的配置文件
新建一个application-context-mongo.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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.1.xsd">
<!-- Connection to MongoDB server -->
<mongo:db-factory host="${mongo.host}" port="${mongo.port}" username="${mongo.user}" password="${mongo.pass}"
dbname="${mongo.dbname}" />
<mongo:mapping-converter id="converter"
db-factory-ref="mongoDbFactory" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<!-- MongoDB GridFS Template -->
<bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
<constructor-arg ref="mongoDbFactory" />
<constructor-arg ref="converter" />
</bean>
</beans>
其中
mongo.host:mongo安装的主机IP
mongo.port:端口号,默认是27017
mongo.user&mongo.pass:mongo默认登录是不需要用户名和密码的
mongo.dbname:你自己创建的mongo数据库名
引入这个配置文件
1.在web.xml中引入
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/application-context-mongo.xml
</param-value>
</context-param>
2.在已经引入的spring配置文件中引入
<import resource="application-context-mongo.xml" />
图片上传
页面
<form name="serForm" action="/fileUpload/upload" method="post" enctype="multipart/form-data">
<h1>采用流的方式上传文件</h1>
<input type="file" name="file">
<input type="submit" value="upload"/>
</form>
后台java代码,这边代码比较简单,当然可以加入文件名校验,文件大小校验等
@RequestMapping(value = "/fileUpload/upload")
@ResponseBody
public String uploadLicence1(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
String originalName = file.getOriginalFilename();
String newName = DateUtil.getCurrentTime() + originalName;
long size = file.getSize();
String artifactId = IdGenerator.createNewId();
gridFsTemplate.store(file.getInputStream(), newName);//将图片存到mongoDB中
saveArtifact(artifactId,originalName,newName,size);//将图片信息存到Mysql数据库中的图片表中
String jsonResult = "{"success":true}";
return jsonResult;
} catch (Exception e) {
System.out.println(e.toString());
return getBadJsonResult(e.toString());
}
} else {
return getBadJsonResult("文件为空");
}
}
图片显示
这边前端用的是Springfreemarker
前端代码
<img id="pic" name="pic" src="${wwwroot}/artifact/pic?id=${artifact.id}">
后端java代码
@RequestMapping(value = "/artifact/pic")
public void photo(String id,HttpServletResponse response) {
GridFSDBFile file = gridFsTemplate.findOne(new Query().addCriteria(Criteria.where("filename").is(id)));
if (file != null) {
try {
response.setContentType(file.getContentType());
response.setContentLength((new Long(file.getLength()).intValue()));
response.setHeader("content-Disposition", "attachment; filename=" + file.getFilename());// "attachment;filename=test.xls"
// copy it to response's OutputStream
OutputStream out = response.getOutputStream();
file.writeTo(out);
out.flush();
out.close();
} catch (IOException ex) {
logger.error("IOError writing file to output stream");
}
}
}