项目需要用的mongodb来存储文件
首先配置在spring配置文件中配置mongodb
1.需要的jar包(maven依赖)
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>
2.spring 配置文件配置 applicationContext-mongodb.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
<!-- ignore-unresolvable 需要配成true 多xml读取配置文件时都需要加上 否则报错 -->
<context:property-placeholder location="classpath:config/mongo.properties" ignore-unresolvable="true" />
<!-- mongo 配置start -->
<!--
connections-per-host: 每个主机答应的连接数(每个主机的连接池大小),当连接池被用光时,会被阻塞住
max-wait-time: 被阻塞线程从连接池获取连接的最长等待时间(ms)
connect-timeout:在建立(打开)套接字连接时的超时时间(ms)
socket-timeout:套接字超时时间;该值会被传递给Socket.setSoTimeout(int)
slave-ok:指明是否答应驱动从次要节点或者奴隶节点读取数据
-->
<mongo:mongo id="mongo" replica-set="${mongo.replicaSet}">
<mongo:options
connections-per-host="${mongo.connectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongo.connectTimeout}"
max-wait-time="${mongo.maxWaitTime}"
auto-connect-retry="${mongo.autoConnectRetry}"
socket-keep-alive="${mongo.socketKeepAlive}"
socket-timeout="${mongo.socketTimeout}"
slave-ok="${mongo.slaveOk}"
write-number="${mongo.writeNumber}"
write-timeout="${mongo.riteTimeout}"
write-fsync="${mongo.writeFsync}"/>
</mongo:mongo>
<!-- 设置使用的数据库 名-->
<mongo:db-factory id="mongoDbFactory" dbname="file" mongo-ref="mongo"/>
<!-- mongodb的模板 -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
<!-- mongo 配置end -->
</beans>
详细配置可参见spring官方配置文件
然后springMvc 上传配置文件配置
1.需要的jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
2.springMvc 配置
<!-- 定义文件上传解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设定文件上传的最大值5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
上传工具类封装FileUpAndDownLoadService .java
package com.r2cf.interactiveweb.service;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
/**
* 文件上传下载工具类
* @author zhangpeng
*
*/
/**
* @author zhangpeng
*
*/
@Service
public class FileUpAndDownLoadService {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 获取mongodb数据库文件操作对象
* @return
*/
private GridFS getGridFS(){
DB db = mongoTemplate.getDb();
GridFS gridFS= new GridFS(db,"fs");
return gridFS;
}
/**
* 文件上传
* @param request
* @return
* @throws IOException
*/
public void upload(HttpServletRequest request,BigDecimal userId) throws IOException{
GridFS gridFS= getGridFS();
GridFSFile file = null;
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = mRequest.getFileMap();
Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, MultipartFile> entry = it.next();
MultipartFile mFile = entry.getValue();//获取文件
file = gridFS.createFile(mFile.getInputStream());// 创建gridfs文件
file.put("filename", mFile.getOriginalFilename());
file.put("userId", userId.toString());
file.put("uploadDate", new Date());
file.put("contentType",mFile.getContentType());
file.save();
}
}
/**
* 查看文件
* @param params k-v 搜索条件
* @return
*/
public List<GridFSDBFile> viewFiles(Map<String,String> params){
GridFS gridFS= getGridFS();
BasicDBObject basicDBObject = new BasicDBObject();
for(Map.Entry<String, String> entry:params.entrySet()){
String key= entry.getKey();
String value=entry.getValue();
basicDBObject.append(key, value);
}
List<GridFSDBFile> list = gridFS.find(basicDBObject);
return list;
}
/**
* 文件查看与下载
* @param id 文件唯一标示id
* @param response
* @throws IOException
*/
public void downLoad(String id,HttpServletResponse response) throws IOException{
GridFS gridFS= getGridFS();
ObjectId objId = new ObjectId(id);
GridFSDBFile gridFSDBFile =(GridFSDBFile)gridFS.findOne(objId);
if (gridFSDBFile != null) {
OutputStream sos = response.getOutputStream();
response.setContentType("application/octet-stream");
// 获取原文件名
String name = (String) gridFSDBFile.get("filename");
String fileName = new String(name.getBytes("utf-8"), "ISO8859-1");
// 设置下载文件名
response.addHeader("Content-Disposition", "attachment; filename=\""
+ fileName + "\"");
// 向客户端输出文件
gridFSDBFile.writeTo(sos);
sos.flush();
sos.close();
}
}
/**
* 单文件删除
* @param id 文件唯一标识
* @return
*/
public String delete(String id){
GridFS gridFS= getGridFS();
ObjectId objId = new ObjectId(id);
gridFS.remove(objId);
return "success";
}
}