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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
@RestController
@RequestMapping("/images")
@RequiredArgsConstructor
public class ImageController {
@Autowired
private ImageRepository images;
private final ReactiveGridFsTemplate gridFsTemplate;
@PostMapping(path = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<ResponseEntity<Void>> upload(@RequestPart("file") Mono<FilePart> fileParts,@RequestParam("description") String description) {
return fileParts
.flatMap(part -> this.gridFsTemplate.store(part.content(), part.filename()))
.flatMap(id -> this.images.save(Image.builder().description(description).gridId(id.toHexString()).build()))
.map( r -> ResponseEntity.ok().<Void>build());
}
@GetMapping("/download/{id}")
public Flux<Void> read(@PathVariable String id, ServerWebExchange exchange) {
return this.gridFsTemplate.findOne(query(where("_id").is(id)))
.flatMap(gridFsTemplate::getResource)
.flatMapMany(r -> {
exchange.getResponse().getHeaders().setContentType(MediaType.IMAGE_PNG);
exchange.getResponse().getHeaders().setCacheControl(CacheControl.maxAge(Duration.ofSeconds(3600)).cachePrivate());
return exchange.getResponse().writeWith(r.getDownloadStream());
});
}
@GetMapping("/find/")
public Flux<Image> getAllAll()
{
return images.findAll();
}
@GetMapping("/find/{idItem}")
public Mono<Image> getById(@PathVariable String idItem){
return images.findById(idItem);
}
@DeleteMapping("/delete/{idItem}")
public Mono<ResponseEntity<Void>> delete(@PathVariable String idItem)
{
return images.deleteById(idItem)
.map( r -> ResponseEntity.ok().<Void>build())
.defaultIfEmpty(ResponseEntity.notFound().build());
}
@DeleteMapping("/deleteGrid/{idGrid}")
public Mono<ResponseEntity<Void>> deleteGrid(@PathVariable String idGrid)
{
return gridFsTemplate.delete(query(where("_id").is(idGrid)))
.map( r -> ResponseEntity.ok().<Void>build())
.defaultIfEmpty(ResponseEntity.notFound().build());
}
} |
Partager