1. 程式人生 > >如何用spring整合mongodb實現檔案上傳

如何用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);
		}
	}