使用GridFsTemplate在mongodb中存取文件

濮嘉茂
2023-12-01

Maven依赖(还有一些springboot需要的)

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
    </parent>

    <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>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

配置GridFsTemplate


import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories
// 读取配置文件的,通过Environment读取
@PropertySource("classpath:mongo.yml")
public class GridFsConfiguration extends AbstractMongoConfiguration {


    @Autowired
    Environment env;

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

    @Override
    protected String getDatabaseName() {
        return env.getProperty("database");
    }

    @Override
    public Mongo mongo() throws Exception {
        return new MongoClient(env.getProperty("host"));
    }

    @Bean
    public MongoDbFactory mongoDbFactory() throws Exception {
        return new SimpleMongoDbFactory(new MongoClient(env.getProperty("host"), env.getProperty("port", Integer.class)), getDatabaseName());
    }

}

mongo.yml

mongo:
  host: 127.0.0.1
  port: 27017
  database: filecenter

使用GridFsTemplate存取文件

import com.mongodb.gridfs.GridFSDBFile;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.test.context.junit4.SpringRunner;

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

import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.gridfs.GridFsCriteria.whereFilename;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = GridFsConfiguration.class)
public class MongoTest {
    @Autowired
    GridFsTemplate gridFsTemplate;

    // 存文件
    @Test
    public void storeFileInGridFs() {
        Resource file = new ClassPathResource("mongo.yml");
        // Resource file = new FileSystemResource("C:\\Users\\Chenggaowei\\Downloads\\Adblock.crx");
        try {
            gridFsTemplate.store(file.getInputStream(), file.getFilename(), "yml");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 下载文件
    @Test
    public void findFilesInGridFs() throws IOException {
        List<GridFSDBFile> result = gridFsTemplate.find(query(whereFilename().is("mongo.yml")));
        GridFSDBFile gridFSDBFile = result.get(0);
        gridFSDBFile.writeTo(new File("C:\\Users\\Chenggaowei\\Downloads\\" + gridFSDBFile.getFilename()));

    }
    // 所有文件
    @Test
    public void readFilesFromGridFs() {
        GridFsResource[] txtFiles = gridFsTemplate.getResources("*");
        for (GridFsResource txtFile : txtFiles) {
            System.out.println(txtFile.getFilename());
        }
    }

}

参考文献

https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#gridfs

 类似资料: