프로필사진

Go, Vantage point

가까운 곳을 걷지 않고 서는 먼 곳을 갈 수 없다.


Github | https://github.com/overnew/

Blog | https://everenew.tistory.com/





티스토리 뷰

반응형

 

 

 

MongoDB의 document의 최대 크기는 16MB이다.

따라서 여러 사진이 저장되는 document는 16MB를 초과하여 저장되지 않는 오류가 발생할 수 있다.

이때는 GridFS를 이용하여 데이터를 분할 저장한다.

 

 

https://medium.com/nerd-for-tech/file-upload-with-springboot-and-mongodb-76a8f5b9f75d

 

 

GridFS는 두가지 종류의 document를 사용해서 저장된다.

이는 위의 그림에서 확인할 수 있듯이 fs.files와 fs.chunks이다.

 

 

fs.files는 해당 데이터의 정보(크기, 생성 일시, 이름 등)이 저장되어 있고, 원하는 metaData도 삽입할 수 있다.

실질적인 대용량 데이터는 fs.chunks들에 256KB 크기로 분할되어 저장된다.

chunk들이 자신의 상위 file의 id값을 가져서 참조하게된다.

 

 

 

files 데이터

 

 

 

chunk 데이터, 각 chunk도 id를 가지는 document다

 

 

 

Configuration 설정

@Configuration
@EnableMongoRepositories(basePackages = "com....")
@RequiredArgsConstructor
public class Config {
private final MongoDatabaseFactory mongoDatabaseFactory;
private final MongoTemplate mongoTemplate;
@Autowired
private MappingMongoConverter mongoConverter;
@Bean
public GridFsTemplate gridFsTemplate() throws Exception {
return new GridFsTemplate(mongoDatabaseFactory, mongoConverter);
}
}
view raw Config.java hosted with ❤ by GitHub

 

GridFS 파일 저장

class GridFsTest{
@Autowired
private GridFsTemplate gridFsTemplate;
@Autowired
private GridFsOperations operations;
private String saveGridFs(String name, InputStream inputStream){
BasicDBObject meta = new BasicDBObject(); //원하는 metaData를 key-value 형식으로 저장
meta.put("key", "value");
meta.put("type", "png");
ObjectId id = gridFsTemplate.store(inputStream, name, meta);
return id.toString();
}
}
view raw saveGridFs.java hosted with ❤ by GitHub

이때의 inputStream으로 이미지나 대용량 파일과 같은 데이터를 저장시킬 수 있다.

 

본인의 경우 이미지 파일을 가지는 document의 field중 하나로 GridFS file id를 String으로 저장하였다.

 

 

 

 

 

이미지 불러오기

 

 

document(당신의 MongoDb collection) 는 imageId 값을 가지고 있고 GridFsTemplate통해 찾아오면 이미지 파일을 전송 시킬 수 있다.

 

@ResponseBody
@RequestMapping(value = "/{id}/image", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testImage(@PathVariable String id) throws IOException {
Document document = repository.findById(id).get();
GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(document.getImageId())));
GridFsResource resource = operations.getResource(file);
InputStream inputStream = resource.getInputStream();
return inputStream.readAllBytes();
}
view raw testImage.java hosted with ❤ by GitHub

 

 

 

 

 

 

참조 

 

https://www.baeldung.com/spring-data-mongodb-gridfs

 

https://mkyong.com/mongodb/spring-data-mongodb-save-binary-file-gridfs-example/

 

https://medium.com/nerd-for-tech/file-upload-with-springboot-and-mongodb-76a8f5b9f75d

 

반응형
댓글
반응형
인기글
Total
Today
Yesterday
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함