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(); } }
标签:mongo,mongodb,response,import,id,GridFSBucket From: https://www.cnblogs.com/northeastTycoon/p/18084950