java:mongodb存储、删除图片

初始mongodb存储删除, 图片,闲言少叙,上代码:

//须引入mongodb的java驱动包
private MongoTemplate mongoTemplate;

public void setMongoTemplate(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}
/**
	 * mongodb存储图片
	 * @param picFile
	 * @param imageUrl
	 * @param gridName节点名,相当于表名
	 */
	public void savePic(File picFile,String imageUrl,String gridName){
         try {
			DB db = mongoTemplate.getDb();
			GridFS fs = new GridFS(db, gridName);
			GridFSInputFile inputFile = fs.createFile(picFile);
			inputFile.setFilename(imageUrl);
			inputFile.setContentType(imageUrl.substring(imageUrl.lastIndexOf(".")));
			inputFile.save();
		} catch (IOException e) {
			e.printStackTrace();
		}
}


/**
	 * 删除图片
	 * @param lunboInfoDto
	 * @param gridName
	 */
	public void deletePic(String imageUrl,String gridName){
       DB db = mongoTemplate.getDb();
		GridFS fs = new GridFS(db, gridName);
		GridFSDBFile file = fs.findOne(imageUrl);
		fs.remove(file);
}

配置文件:
<bean id="pictureTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongodbFactory"></constructor-arg>
    </bean>

 

你可能感兴趣的:(java,mongodb,删除,图片,存储)