mongo GridFSBucket

东北大亨發表於2024-03-20

1、描述:mongo 單機使用 GridFSBucket

2、pox中新增jar

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.12.9</version>
</dependency>

3、module中使用,直接上程式碼

3.1 configuration 的bean建立

import com.mongodb.client.*;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author :tycoon
 * @description :mongo utility
 * @version: V1.0.0
 * @create :2024-03-20 12:13:25
 */
@Configuration
public class GridFSBucketConfig {

    @Value("${spring.data.mongodb.database}")
    private String db;
    @Resource
    private MongoClient mongoClient;

    /**
     * 建立預設的bucket, bucket name: fs
     */
    @Bean
    public GridFSBucket getGridFSBucket() {
        MongoDatabase database = mongoClient.getDatabase(db);
        return GridFSBuckets.create(database);
    }
 }

3.2 儲存圖片之mongo中

/**
 * @author :tycoon
 * @description :接收圖片轉換目標圖儲存到mongo資料庫中
 * @version: V1.0.0
 * @create :2023-09-29 23.23:25
 */
@Controller
public class ImageController {

    @Autowired
    private GridFSBucket gridFSBucket;

    @GetMapping("imagePreview/{id}")
    public void imagePreview(@PathVariable("id") String id,HttpServletResponse response) throws IOException {

        Document query = new Document("_id", new ObjectId(id));
        GridFSFile file = gridFSBucket.find(query).first();

        if(file == null){
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //響應頭
        response.setContentType("image/png");
        // 獲取檔案流
        OutputStream outputStream = response.getOutputStream();
        gridFSBucket.downloadToStream(file.getObjectId(),outputStream);
        outputStream.close();
    }
}


相關文章