GridFS文件操作

article/2025/10/14 14:03:02

1. GridFS介绍

GridFSMongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFS可以快速集成
开发。
它的工作原理是:
GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合
collection)存储文件,一个集合是chunks, 用于存储文件的二进制数据;一个集合是files,用于存储文件的元数据信息(文件名称、块大小、上传时间等信息)。
GridFS中读取文件要对文件的各各块进行组装、合并。
详细参考:https://docs.mongodb.com/manual/core/gridfs/

2. GridFS 存取文件测试

2.1 新建项目配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.2.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>demo-monogo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo-monogo</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

2.2 在application.yml配置mongodb

spring:data:mongodb:uri: mongodb://root:root@localhost:27017database: xc_cms

2.3 GridFS存取文件测试

1、存文件
使用GridFsTemplate存储文件测试代码:
向测试程序注入GridFsTemplate

package com.example.demomonogo;import org.bson.types.ObjectId;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;@SpringBootTest
class DemoMonogoApplicationTests {@AutowiredGridFsTemplate gridFsTemplate;@Testpublic void testGridFs() throws FileNotFoundException {//要存储的文件File file = new File("D:\\test\\user_selected.png");//定义输入流FileInputStream inputStram = new FileInputStream(file);//向GridFS存储文件ObjectId objectId = gridFsTemplate.store(inputStram, "user_selected.png", "image/png");//得到文件IDString fileId = objectId.toString();System.out.println(fileId);}}

文件以及成功被存入到GridFS

2.4 读取文件

1)在config包中定义Mongodb的配置类,如下:
GridFSBucket用于打开下载流对象

package com.example.demomonogo.config;/*** @author john* @date 2019/12/21 - 10:39*/import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MongoConfig {@Value("${spring.data.mongodb.database}")String db;@Beanpublic GridFSBucket getGridFSBucket(MongoClient mongoClient) {MongoDatabase database = mongoClient.getDatabase(db);GridFSBucket bucket = GridFSBuckets.create(database);return bucket;}
}

2)测试代码如下

package com.example.demomonogo;import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;@SpringBootTest
class DemoMonogoApplicationTests {@AutowiredGridFsTemplate gridFsTemplate;@AutowiredGridFSBucket gridFSBucket;@Testpublic void queryFile() throws IOException {String fileId = "5dfd851306322e6b12057a40";//根据id查询文件GridFSFile gridFSFile =gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));//打开下载流对象GridFSDownloadStream gridFSDownloadStream =gridFSBucket.openDownloadStream(gridFSFile.getObjectId());//创建gridFsResource,用于获取流对象GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);//获取流中的数据InputStream inputStream = gridFsResource.getInputStream();File f1 = new File("D:\\test\\get.png");if (!f1.exists()) {f1.getParentFile().mkdirs();}byte[] bytes = new byte[1024];// 创建基于文件的输出流FileOutputStream fos = new FileOutputStream(f1);int len = 0;while ((len = inputStream.read(bytes)) != -1) {fos.write(bytes, 0, len);}inputStream.close();fos.close();}}

2.5 删除文件

package com.example.demomonogo;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;import java.io.IOException;@SpringBootTest
class DemoMonogoApplicationTests {@AutowiredGridFsTemplate gridFsTemplate;//删除文件@Testpublic void testDelFile() throws IOException {//根据文件id删除fs.files和fs.chunks中的记录gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5dfd851306322e6b12057a40")));}}


http://chatgpt.dhexx.cn/article/uXdd1935.shtml

相关文章

MongoDB GridFS

GridFS简介 GridFS是Mongo的一个子模块,使用GridFS可以基于MongoDB来持久存储文件。并且支持分布式应用(文件分布存储和读取)。作为MongoDB中二进制数据存储在数据库中的解决方案&#xff0c;通常用来处理大文件&#xff0c;对于MongoDB的BSON格式的数据(文档)存储有尺寸限制&a…

GridFS详细分析

GridFS简介 GridFS是MongoDB中的一个内置功能&#xff0c;可以用于存放大量小文件。 http://www.mongodb.org/display/DOCS/GridFS http://www.mongodb.org/display/DOCS/GridFSSpecification GridFS使用 MongoDB提供了一个命令行工具mongofiles可以来处理GridFS&#xff…

13.MongoDB之Gridfs

参照官网如下(如下链接依次递进)&#xff1a; https://docs.mongodb.com/manual/core/gridfs/ https://docs.mongodb.com/database-tools/mongofiles/#mongodb-binary-bin.mongofiles https://docs.mongodb.com/database-tools/installation/installation/ FS&#xff1a;即文…

MongoDB(四)——GridFS

GridFS MongoDB的一个重要子模块&#xff0c;可基于MongoDB来持久存储文件&#xff0c;并且支持分布式存储和读取。 持久存储&#xff1a;对应瞬时数据如内存&#xff0c;指保存到数据库中&#xff0c;能持久保存。 分布式存储&#xff1a;将数据分散地存储于多个位置。 存在的…

在Keil MDK中无法使用gmtime函数进行时间戳转换

硬件平台STM32&#xff0c;软件平台Keil MDK 5.18 由于项目中需要用到UNIX时间戳和日历的来回转换&#xff0c;于是想到C库函数<time.h>里面有现成的函数可以使用。 于直接使用mktime和gmtime两个函数进行时间戳转换&#xff0c;前者把日历转为时间戳&#xff0c;后者把…

C++中获取日期函数gmtime和localtime区别

函数gmtime和localtime的声明如下&#xff1a; struct tm * gmtime (const time_t * timer); struct tm * localtime (const time_t * timer); 它们均接收一个time_t的const指针类型&#xff0c;time_t类型通常是一个大整数值&#xff0c;该整数值表示自UTC时间1970年1月1日0…

C语言学习笔记---时间函数ctime()和gmtime()

函数原型如下&#xff1a; __CRT_INLINE char *__cdecl ctime(const time_t *_Time);__CRT_INLINE struct tm *__cdecl gmtime(const time_t *_Time);ctime函数 ctime函数可以将当前时间值转换为字符串格式返回。返回的字符串格式为&#xff1a;Www Mmm dd hh:mm:ss yyyy 其中&…

Linux系统编程一:时间和延时、gmtime和localtime函数返回相同

目录 1. 概述2. 延时函数3. 当前时间3.1 时间调用函数3.2 时间转换函数 4. gmtime和localtime函数返回相同测试代码 1. 概述 前面的几篇文章Linux学习笔记一到七&#xff0c;主要是开发环境的搭建&#xff0c;都是一些准备工作。从本篇文章开始&#xff0c;将学习Linux系统编程…

逆向 time.h 函数库 time、gmtime 函数

0x01 time 函数 函数原型&#xff1a;time_t time(time_t *t)函数功能&#xff1a;返回自纪元 Epoch(1970-01-01 00:00:00 UTC)起经过的时间&#xff0c;以秒为单位。如果 seconds 不为空&#xff0c;则返回值也存储在变量 seconds 中C\C 实现&#xff1a; #include <stdio.…

python gmtime_在Python中操作日期和时间之gmtime()方法的使用

在Python中操作日期和时间之gmtime()方法的使用 这篇文章主要介绍了在Python中操作日期和时间之gmtime()方法的使用,是Python入门学习中的基础知识,需要的朋友可以参考下 gmtime()方法转换历元到一struct_time以UTC其中dst的标志值始终为0以秒表示时间。如果不设置秒时或None&a…

gmtime与localtime的区别

目录 gmtime函数 linux环境下&#xff1a; window环境下 localtime函数 gmtime函数 gmtime转换的时间是UTL时间&#xff0c;与北京时间相差了8个小时 如果你想要得到北京时间&#xff0c;不建议你将gmtime转换后的时间直接加上八个小时 linux环境下&#xff1a; 执行结…

【C库函数】strerror函数详解

目录 strerror 函数原型 参数详解 返回值详解 函数讲解 strerror 返回错误码&#xff0c;所对应的错误信息 函数原型 char *strerror( int errnum ); 参数详解 参数errnum解析错误码信息(errno) 返回值详解 strerror函数就是返回这些错误码所对应错误信息的字符串起始地…

详解:strerror函数:将错误码转化为错误信息

对于大家在浏览网页的时候&#xff0c;或多或少的会见识过不少的错误信息&#xff1a;比如&#xff1a;最常见的就是&#xff1a;404 但是&#xff0c;使用strerror函数&#xff0c;可以将错误码转化为错误信息&#xff01;不知道偶然间看见的读者是否有兴趣进行深入研究一下&…

Strerror函数和Perror函数的介绍及使用

Strerror 通过标准错误的标号&#xff0c;获得错误的描述字符串 &#xff0c;将单纯的错误标号转为字符串描述&#xff0c;方便用户查找错误。 需要引用的头文件 #include <errno.h> #include <string.h> 用法&#xff1a;如果调用函数失败&#xff0c;会产生错误码…

strerror函数使用

。 char *strerror(int errnum); 功能&#xff1a;通过标准错误的标号&#xff0c;获得错误的描述字符串 &#xff0c;将单纯的错误标号转为字符串描述。 参数&#xff1a;errnum&#xff1a;最新的错误标号。 返回值&#xff1a;指向错误信息的指针。#include <stdio.h>…

Linux 应用编程之strerror函数

在 Linux 系统下对常见的错误做了一个编号&#xff0c;每一个编号都代表着每一种不同的错误类型&#xff0c;当函数执行发生错误的时候&#xff0c;操作系统会将这个错误所对应的编号赋值给 errno 变量&#xff0c;每一个进程&#xff08;程序&#xff09;都维护了自己的 errno…

C语言函数: 字符串函数及模拟实现strtok()、strstr()、strerror()

C语言函数&#xff1a; 字符串函数及模拟实现strtok()、strstr()、strerror() strstr()函数: 作用&#xff1a;字符串查找。在一串字符串中&#xff0c;查找另一串字符串是否存在。 形参: str2在str1中寻找。返回值是char*的指针 原理&#xff1a;如果在str1中找到了str2&…

【strerror函数的使用】

strerror函数的使用 一&#xff0c;说明二&#xff0c;具体使用场景 一&#xff0c;说明 strerror会返回错误码&#xff0c;我们可以将其翻译成所对应的错误信息&#xff1b; c语言的库函数在运行的时候&#xff0c;如果发生错误&#xff0c;就会将错误码存放在一个变量中&…

strerror 函数

收藏 75 23 strerror编辑 本词条缺少 名片图&#xff0c;补充相关内容使词条更完整&#xff0c;还能快速升级&#xff0c;赶紧来 编辑吧&#xff01; 通过标准错误的标号&#xff0c;获得错误的描述字符串 &#xff0c;将单纯的错误标号转为字符串描述&#xff0c;方便用户查找…

strerror函数介绍

认识strerror 库函数调用失败的时候会产生错误码&#xff0c;而每一个错误码对应着一条错误信息&#xff0c;strerror函数的作用就是将错误码给转化成错误信息。 在C语言中有一条全局的错误码errno&#xff0c;在程序运行过程中&#xff0c;只要库函数调用失败&#xff0c;我们…