如何用spring集成mongodb实现文件上传

首先要把必要的mongoDB需要的jar加进项目中

定义mongoDB的bean

<bean id="mongoClient" class="com.mongodb.MongoClient">
	
		
		<constructor-arg index="0" type="java.lang.String" name="host" value="127.0.0.1" />					
		<constructor-arg index="1" type="int" name="port" value="27017" />
	</bean>
自定义实现mongodb增删改实体类

<bean id="mongoDB" class="com.test.MongoDB">
		<property name="mongoClient" ref="mongoClient" />
		<property name="dbName" value="orcl" />
	</bean>
定义mongoClient基础类


public class MongoDB {

	private MongoClient mongoClient;
	private String dbName;
	
	/**
	 * 获取名为dbName数据库
	 * 
	 * @return
	 */
	public DB getDB() {
		return mongoClient.getDB(dbName);
	}

	public MongoClient getMongoClient() {
		return mongoClient;
	}

	public void setMongoClient(MongoClient mongoClient) {
		this.mongoClient = mongoClient;
	}

	public String getDbName() {
		return dbName;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

}
定义mongodb操作Dao类

/**
	 * 增
	 * 
	 * @param bean
	 * @return
	 */
	public T save(T bean) {
		String beanJson = JsonUtil.getJSONString(bean);
		DBCollection collection = mongoDB.getDB().getCollection(clazz.getSimpleName());
		collection.save((DBObject)JSON.parse(beanJson));
		return bean;
	}

	/**
	 * 删
	 * @param id
	 */
	public void remove(String id) {
		DBCollection collection = mongoDB.getDB().getCollection(clazz.getSimpleName());
		BasicDBObject doc = new BasicDBObject();
		doc.put("_id", id);
		collection.remove(doc);
	}

	/**
	 * 改
	 * @param query
	 * @param newDoc
	 */
	public void update(BasicDBObject query, BasicDBObject newDoc) {
		DBCollection collection = mongoDB.getDB().getCollection(clazz.getSimpleName());
		collection.update(query, newDoc);
	}
定义保存文件类

/**
	 * 保存文件到MongoDB GridFS
	 * 
	 * @param in			- 需要保存文件的输入流
	 * @param id			- 需要保存文件的唯一ID
	 * @param fileName		- 需要保存文件的文件名
	 * @param contentType  - 需要保存文件的文件类型
	 * @param downloadName - 需要保存文件被下载时的文件名
	 */
	public void save(InputStream in, String id, String fileName, String contentType, String downloadName) {
		GridFS fs = new GridFS(mongoDB.getDB(), this.getClass().getSimpleName());
		GridFSInputFile fsFile = fs.createFile(in);
		fsFile.setId(id);
		fsFile.setFilename(fileName);
		fsFile.setContentType(contentType);
		fsFile.put("downloadName", downloadName);
		fsFile.save();
	}
	
	/**
	 * 从MongoDB GridFS文件系统中删除指定ID的文件
	 * 
	 * @param id
	 */
	public void remove(String id) {
		GridFS fs = new GridFS(mongoDB.getDB(), this.getClass().getSimpleName());
		BasicDBObject query = new BasicDBObject("_id", id);
		fs.remove(query);
	}
	
	/**
	 * 从MongoDB GridFS文件系统中批量删除指定ID的文件
	 * @param ids
	 */
	public void batchRemove(String... ids) {
		GridFS fs = new GridFS(mongoDB.getDB(), this.getClass().getSimpleName());
		for(String id : ids){
			BasicDBObject query = new BasicDBObject("_id", id);
			fs.remove(query);
		}
	}








展开阅读全文

没有更多推荐了,返回首页