对于最新的稳定版本,请使用 Spring Data MongoDB 4.4.0spring-doc.cadn.net.cn

GridFS 支持

MongoDB 支持将二进制文件存储在其文件系统 GridFS 中。 Spring Data MongoDB 提供了一个GridFsOperationsReactiveGridFsOperationsinterface 以及相应的实现,GridFsTemplateReactiveGridFsTemplate,以便与文件系统交互。 您可以通过向模板实例发送MongoDatabaseFactory/ReactiveMongoDatabaseFactory以及MongoConverter,如下例所示:spring-doc.cadn.net.cn

class GridFsConfiguration extends AbstractMongoClientConfiguration {

  // … further configuration omitted

  @Bean
  public GridFsTemplate gridFsTemplate() {
    return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
  }
}

现在可以注入模板并用于执行存储和检索作,如下例所示:spring-doc.cadn.net.cn

使用 GridFS 存储文件
class GridFsClient {

  @Autowired
  GridFsOperations operations;

  @Test
  public void storeFileToGridFs() {

    FileMetadata metadata = new FileMetadata();
    // populate metadata
    Resource file = … // lookup File or Resource

    operations.store(file.getInputStream(), "filename.txt", metadata);
  }
}

store(…)作采用InputStream、文件名和(可选)有关要存储的文件的元数据信息。 元数据可以是任意对象,该对象将由MongoConverter配置了GridFsTemplate. 或者,您也可以提供Document.spring-doc.cadn.net.cn

您可以通过find(…)getResources(…)方法。 我们来看看find(…)方法。 您可以找到单个文件或多个文件,这些文件与Query. 您可以使用GridFsCriteriahelper 类来定义查询。 它提供了静态工厂方法来封装默认元数据字段(例如whereFilename()whereContentType()) 或自定义whereMetaData(). 以下示例演示如何使用模板查询文件:spring-doc.cadn.net.cn

使用 GridFsTemplate 查询文件
class GridFsClient {

  @Autowired
  GridFsOperations operations;

  @Test
  public void findFilesInGridFs() {
    GridFSFindIterable result = operations.find(query(whereFilename().is("filename.txt")));
  }
}
目前,MongoDB 不支持在从 GridFS 检索文件时定义排序条件。因此,在Query实例传递到find(…)方法被忽略。

从 GridFs 读取文件的另一个选项是使用ResourcePatternResolver接口。 它们允许将 Ant 路径传递到方法中,因此可以检索与给定模式匹配的文件。 以下示例演示如何使用GridFsTemplate要读取文件:spring-doc.cadn.net.cn

使用 GridFsTemplate 读取文件
class GridFsClient {

  @Autowired
  GridFsOperations operations;

  public GridFsResources[] readFilesFromGridFs() {
     return operations.getResources("*.txt");
  }
}

GridFsOperations延伸ResourcePatternResolver并让GridFsTemplate(例如)插入ApplicationContext从 MongoDB 数据库中读取 Spring Config 文件。spring-doc.cadn.net.cn

默认情况下,GridFsTemplate获得GridFSBucket第一次 GridFS 交互时。 之后,模板实例将重用缓存的存储桶。 要使用不同的存储桶,请从同一个 Template 实例使用接受Supplier<GridFSBucket>.

APP信息