MongoDB-4 GridFS 文件存储

原创
03/03 09:24
阅读数 68

1. 配置config

spring:
  data:
    mongodb:
      uri: mongodb://username:password@192.168.2.72:27017
      database: mydb
@Component
public class WebConfig {
    @Value("${spring.data.mongodb.database}")
    private String mongodb;

    @Bean
    public GridFSBucket getGridFSBucket(MongoClient mongoClient){
        MongoDatabase database = mongoClient.getDatabase(mongodb);
        GridFSBucket bucket = GridFSBuckets.create(database);
        return bucket;
    }

}

2. 基于gridfs的上传,读取与下载

@Autowired
    private GridFSBucket gridFSBucket;


    /**
     * 创建文件到GirdFS
     * @param model
     * @return
     * @throws Exception
     */
    @GetMapping("/addToGridFS")
    @ResponseBody
    public Object addToGirdFS(Model model) throws Exception {

        // 声明freemarker的配置类
        Configuration cfg = new Configuration(Configuration.getVersion());
        // 声明freemarker模板所需要加载的目录位置
        String classpath = this.getClass().getResource("/").getPath();
        cfg.setDirectoryForTemplateLoading(new File(classpath + "templates"));
//        System.out.println(classpath + "templates");

        // 构建数据
        model = makeModel(model);

        // 加载ftl模板
        Template template = cfg.getTemplate("user.ftl", "utf-8");
        // 获得静态化后的内容
        String htmlContent = FreeMarkerTemplateUtils.processTemplateIntoString(template, model.asMap());

        InputStream inputStream = IOUtils.toInputStream(htmlContent);

        // 上传
        ObjectId fileId = gridFSBucket.uploadFromStream("1001.html", inputStream);
        System.out.println("上传完成。 文件ID:" + fileId);

        // 文件在mongodb中的id
        return fileId.toString();
    }


    /**
     * 读取文件
     * @param model
     * @return
     * @throws Exception
     */
    @GetMapping("/readGridFS")
    @ResponseBody
    public String readGridFS(Model model) throws Exception {

        // 获取文件ID
        String objectId = "5e42924980fb940ab75f141a"; // 根据upload后文件ID修改
        // 获取内容
        GridFSFindIterable gridFSFindIterable = gridFSBucket.find(Filters.eq("_id", new ObjectId(objectId)));
        GridFSFile gridFSFile = gridFSFindIterable.first();
        System.out.println("filename: " + gridFSFile.getFilename());

        return gridFSFile.getFilename();
    }

    /**
     * 从gridfs中下载文件
     * @throws Exception
     */
    @GetMapping("/downloadGridFS")
    @ResponseBody
    public String downloadGridFS() throws Exception {
        // 获取文件ID
        String objectId = "5e42924980fb940ab75f141a";
        // 获取文件流,定义存放位置和名称
        File file = new File(htmlTarget + "/1001.html");
        // 创建输出流
        OutputStream os = new FileOutputStream(file);
        // 执行下载
        gridFSBucket.downloadToStream(new ObjectId(objectId), os);
        System.out.println("下载成功");
        return "ok";
    }
    @GetMapping("/downloadGridFSByFileName")
    @ResponseBody
    public String downloadGridFSByFileName() throws Exception {
        // 获取文件ID
        String filename = "1001.html";
        // 获取文件流,定义存放位置和名称
        File file = new File(htmlTarget + "/" + filename);
        // 创建输出流
        OutputStream os = new FileOutputStream(file);
        // 执行下载
        gridFSBucket.downloadToStream(filename, os);
        System.out.println("下载成功");
        return "ok";
    }

    /**
     * 删除文件
     * @param model
     * @return
     * @throws Exception
     */
    @GetMapping("/deleteGirdFS")
    @ResponseBody
    public String deleteGirdFS(Model model) throws Exception {
        // 获取文件ID
        String objectId = "5e42924980fb940ab75f141a";
        // 执行删除
        gridFSBucket.delete(new ObjectId(objectId));
        return "ok";
    }

5. 整合SpringBoot作为文件服务展示

当然也能和nginx放在一起使用

    /**
     * 借助nginx+springboot来访问gridfs中的文件内容
     * @param fileName
     * @return
     * @throws Exception
     */
    @GetMapping("/detail/{fileName}")
    public void detail(@PathVariable("fileName") String fileName, HttpServletResponse response) throws Exception {

        response.setContentType("text/html;charset=utf-8");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            gridFSBucket.downloadToStream(fileName, outputStream);
            
// 方式2
//            GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(fileName);
//            GridFsResource gridFsResource = new GridFsResource(gridFSDownloadStream.getGridFSFile(), gridFSDownloadStream);

//            String data = IOUtils.toString(gridFsResource.getInputStream(), "UTF-8");
//            System.out.println(data);

//            out.write(data.getBytes("UTF-8"));
//            out.write("风间影月".getBytes("UTF-8"));
        } finally {
            outputStream.close();
        }
    }
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部