Sprong-boot Mongodb使用GridFs做小型文件服务器

话不多说,直接正题:

compile("org.springframework.boot:spring-boot-starter-data-mongodb")
compile group: 'commons-codec', name: 'commons-codec', version: '1.10'

配置文件:

spring:
  data:
    mongodb:
      database: ***
      host: ***
      username: ***
      password: ***
      port: ***

上传文件代码:

@ResponseBody
@PostMapping(value = "/upload/file")
public String uploadSample(@RequestBody MultipartFile file) {
    try {
        String md5 = DigestUtils.md5Hex(file.getInputStream());
        QueryBuilder builder = new QueryBuilder();
        builder.and("md5").is(md5);
        GridFSDBFile gridFSDBFile = gridFsTemplate.findOne(new BasicQuery(builder.get()));
        if (gridFSDBFile != null) {
            return gridFSDBFile.getId().toString();
        }
        GridFSFile gridFSFile = gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), file.getContentType());
        returngridFSFile.getId().toString();
    } catch (Exception e) {
        throw new RuntimeException("");
    }
}

访问图片代码:

@GetMapping(value = "/get/file/{id}")
public void get(@PathVariable Object id, HttpServletResponse response) throws IOException {
    QueryBuilder builder = new QueryBuilder();
    builder.and("_id").is(id);
    GridFSDBFile file = gridFsTemplate.findOne(new BasicQuery(builder.get()));
    response.setContentType(file.getContentType());
    file.writeTo(response.getOutputStream());
}

spring boot中默认配置可以满足基本需求,文件存储可以使用文件md5去重,非常方便,需要注意的是mongodb存储对文件大小的限制,这个具体数值请自行测试。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值