GridFSBucket SpringBoot MongoDB存取文件代码记录

spring-boot-starter-data-mongodb(2.1.1.RELEASE)、hutool(4.6.1)、lombok

在@Configuration注解类下配置GridFSBucket

    @Autowired
    private MongoDbFactory mongoDbFactory;

    @Bean
    public GridFSBucket getGridFSBuckets() {
        MongoDatabase db = mongoDbFactory.getDb();
        return GridFSBuckets.create(db);
    }

application.yml

spring:
  data:
    mongodb:
      host: localhost
      port: 27017
      database: test   

mongodb 涉及集合fs.chunksfs.files

import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import org.bson.types.ObjectId;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.springframework.data.mongodb.core.MongoTemplate;
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 org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RequestMapping("/login")
@RestController
public class BaseController {
  	@Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private GridFsTemplate gridFsTemplate;
    @Resource
    private GridFSBucket gridfsbucket;

    /**
     * 上传图片文件
     * @param file 上传文件
     * @return 图片文件id
     * @throws IOException
     */
    @PostMapping("/gridFs")
    public String contextLoads(@RequestParam(value = "image") MultipartFile file) throws IOException {
        //向Girdfs存储文件
        ObjectId objectId = gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), StandardCharsets.UTF_8);
        return objectId.toString();
    }

 	/**
     * 返回图片 其他类型的文件 可以指定其余MediaType
     * @param id 图片id
     * @return byte[]
     */
    @GetMapping(value = "/gridFs/{id}", produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_GIF_VALUE})
    public byte[] gridFs1(@PathVariable String id) {

        GridFSDownloadStream downloadStream = null;
        InputStream inputStream = null;
        try {
            //根据id查询文件
            GridFSFile gridfsfile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
            if (ObjectUtil.isNotNull(gridfsfile)) {
                //打开流下载对象
                downloadStream = gridfsbucket.openDownloadStream(gridfsfile.getObjectId());
                //获取流对象
                GridFsResource gridFsResource = new GridFsResource(gridfsfile, downloadStream);
                //获取数据
                inputStream = gridFsResource.getInputStream();
                //可保存到文件到服务器
                //FileUtil.writeFromStream(inputStream, "E:\\FFOutput\\" + gridfsfile.getFilename());
                return IoUtil.readBytes(inputStream);
            }
        } catch (Exception e) {
            log.error("XXX", e);
        } finally {
            IoUtil.close(inputStream);
            IoUtil.close(downloadStream);
        }
        //可以返回默认图片流
        return null;
    }

 	/**
     * 返回图片浏览器下载
     * @param id 图片id
     * @return ResponseEntity
     */
    @GetMapping(value = "/gridFsDownload/{id}")
    public ResponseEntity<byte[]> gridFs(@PathVariable String id) {
        GridFSDownloadStream downloadStream = null;
        InputStream inputStream = null;
        HttpHeaders headers1 = new HttpHeaders();
        MediaType mediaType = new MediaType("text", "html", StandardCharsets.UTF_8);
        headers1.setContentType(mediaType);
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>("下载失败".getBytes(), headers1, HttpStatus.CREATED);
        try {
            //根据id查询文件
            GridFSFile gridfsfile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
            if (ObjectUtil.isNotNull(gridfsfile)) {
                //打开流下载对象
                downloadStream = gridfsbucket.openDownloadStream(gridfsfile.getObjectId());
                //获取流对象
                GridFsResource gridFsResource = new GridFsResource(gridfsfile, downloadStream);
                //获取数据
                inputStream = gridFsResource.getInputStream();
                // 通知浏览器进行文件下载
                String fileName = URLEncoder.encode(gridfsfile.getFilename(), StandardCharsets.UTF_8.name());
                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
                headers.add("content-length", String.valueOf(gridfsfile.getLength()));
                responseEntity = new ResponseEntity<>(IoUtil.readBytes(inputStream), headers, HttpStatus.OK);
            }
        } catch (IOException e) {
            log.error("XXX", e);
            return responseEntity;
        } finally {
            IoUtil.close(inputStream);
            IoUtil.close(downloadStream);
        }
        return responseEntity;
    }
}

你可能感兴趣的:(SpringBoot,MongoDB)