Spring Data MongoDB:保存二进制文件,GridFS示例

Spring Data MongoDB:保存二进制文件,GridFS示例_第1张图片 Spring Data MongoDB:保存二进制文件,GridFS示例_第2张图片

在MongoDB中,您可以使用GridFS来存储二进制文件。 在本教程中,我们向您展示如何使用Spring Data的GridFsTemplate在MongoDB中GridFsTemplate存储图像/从中读取图像。

1. GridFS –保存示例(注释中的Spring配置)

整理一个图像文件并将其保存到MongoDB中。

SpringMongoConfig.java
package com.mkyong.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;

/**
 * Spring MongoDB configuration file
 * 
 */
@Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration{
	
	@Bean
	public GridFsTemplate gridFsTemplate() throws Exception {
		return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
	}

	@Override
	protected String getDatabaseName() {
		return "yourdb";
	}

	@Override
	@Bean
	public Mongo mongo() throws Exception {
		return new MongoClient("127.0.0.1");
	}

}
GridFsAppStore.java
package com.mkyong.core;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.gridfs.GridFsOperations;

import com.mkyong.config.SpringMongoConfig;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

/**
 * GridFs example
 * 
 * @author mkyong
 * 
 */

public class GridFsAppStore {

    public static void main(String[] args) {

	ApplicationContext ctx = 
                     new AnnotationConfigApplicationContext(SpringMongoConfig.class);
	GridFsOperations gridOperations = 
                      (GridFsOperations) ctx.getBean("gridFsTemplate");

	DBObject metaData = new BasicDBObject();
	metaData.put("extra1", "anything 1");
	metaData.put("extra2", "anything 2");

	InputStream inputStream = null;
	try {
		inputStream = new FileInputStream("/Users/mkyong/Downloads/testing.png");
		gridOperations.store(inputStream, "testing.png", "image/png", metaData);

	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} finally {
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

		System.out.println("Done");
    }

}

查看MongoDB控制台,查看已保存的内容。

> show dbs
yourdb	0.203125GB

> use yourdb
switched to db yourdb

> show collections
fs.chunks
fs.files
system.indexes

> db.fs.files.find()
{ "_id" : ObjectId("51641c5630045c9b3db35afc"), "chunkSize" : NumberLong(262144), 
"length" : NumberLong(4238), "md5" : "9969527cd95a5a573f15e953f0036800", "filename" : "testing.png", 
"contentType" : "image/png", "uploadDate" : ISODate("2013-04-09T13:49:10.104Z"), 
"aliases" : null, "metadata" : { "extra1" : "anything 1", "extra2" : "anything 2" } }
>

> db.fs.chunks.find()
{ "_id" : ObjectId("51641c5630045c9b3db35afd"), 
"files_id" : ObjectId("51641c5630045c9b3db35afc"), "n" : 0, 
"data" : BinData(0,"/9j/4AAQSkZJRgABAgAAZ......EQH/9k=") }

图像的信息保存在fs.files ,图像的文件(转换为二进制文件)存储在fs.chunks ,并通过_idfiles_id链接。

2. GridFS –阅读示例(XML文件中的Spring配置)

从MongoDB中读取以上图像文件,并将其另存为另一个图像。

SpringConfig.xml



	
	

	
		
		
	

GridFsAppStore.java
package com.mkyong.core;

import java.io.IOException;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;

/**
 * GridFs example
 * 
 * @author mkyong
 * 
 */

public class GridFsAppRead {

    public static void main(String[] args) {

	ApplicationContext ctx = 
              new GenericXmlApplicationContext("SpringConfig.xml");
	GridFsOperations gridOperations = 
              (GridFsOperations) ctx.getBean("gridFsTemplate");

	List result = gridOperations.find(
               new Query().addCriteria(Criteria.where("filename").is("testing.png")));

	for (GridFSDBFile file : result) {
		try {
			System.out.println(file.getFilename());
			System.out.println(file.getContentType());
				
			//save as another image
			file.writeTo("/Users/mkyong/Downloads/new-testing.png");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	System.out.println("Done");

    }
}

下载源代码

下载它– SpringMongoDB-GridFs-Example.zip (24 KB)

参考文献

  1. AbstractMongoConfiguration JavaDoc
  2. Spring Data MongoDB GridFS支持
  3. Spring Data MongoDB Hello World示例
  4. Java MongoDB:保存图像示例

翻译自: https://mkyong.com/mongodb/spring-data-mongodb-save-binary-file-gridfs-example/

你可能感兴趣的:(Spring Data MongoDB:保存二进制文件,GridFS示例)