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<byte[]>
     */
    @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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章