十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
本篇内容介绍了“GridFS的原理和应用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

专注于为中小企业提供成都网站设计、做网站服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业天等免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了超过千家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用Mongo DB存储数据,使用FGridFS可以快速集成开发。
工作原理:
在GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合(collection)存储文件,一个集合是chunks,用于存储文件的二进制数据;一个集合是files,用于存储文件的元数据(文件名称,大小,上传时间等信息)。
入门代码:
一、添加依赖
org.springframework.boot spring-boot-starter-data-mongodb org.springframework.boot spring-boot-starter-test org.springframework.boot spring-boot-starter-web org.apache.commons commons-io 1.3.2
二、创建启动类
package lianbang.wu.gridfs;
import com.mongodb.MongoClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class GridFSApplication {
public static void main(String[] args) {
SpringApplication.run(GridFSApplication.class);
}
}三、配置文件
server: port: 31001 spring: application: name: xc-service-manage-cms data: mongodb: uri: mongodb://root:123@localhost:27017 #mongodb连接 database: xc-cms #数据库名称
四、创建配置类
@Configuration
public class GridFsConfig {
@Value("${spring.data.mongodb.database}")
String db;
@Bean
public GridFSBucket getGridFSBucket(MongoClient mongoClient){
MongoDatabase database = mongoClient.getDatabase(db);
GridFSBucket bucket = GridFSBuckets.create(database);
return bucket;
}
}五、测试代码
public class GridFSTest {
@Autowired
GridFsTemplate gridFsTemplate;
@Autowired
GridFSBucket gridFSBucket;
//保存文件
@Test
public void testGridFs() throws FileNotFoundException {
File file = new File("d:/index_banner.html");
FileInputStream fileInputStream = new FileInputStream(file);
ObjectId objectId = gridFsTemplate.store(fileInputStream, "测试文件");
String fileId = objectId.toString();
System.out.println(fileId);
}
//读取文件
@Test
public void queryFile() throws IOException {
String fileId = "123456";//模拟的id
GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
String string = IOUtils.toString(gridFsResource.getInputStream(), "utf-8");
System.out.println(string);
}
//删除文件
@Test
public void testDelFile(){
gridFsTemplate.delete(Query.query(Criteria.where("_id").is("1234")));
}
}“GridFS的原理和应用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!