Hey StackExchange
Hey StackExchange

Reputation: 2125

Spring WebFlux: How to store a file in a R2DBC database (PostgreSQL)?

Tried everything I could think of in order to store a file in a table with WebFlux and a R2DBC PostgresDriver without success, while it work with in a non reactive way with SpringMVC.

Non reactive

Controller

    @PostMapping("/upload")
    public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file) {
      String message = "";
      try {
        storageService.store(file);
        message = "Uploaded the file successfully: " + file.getOriginalFilename();
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
      } catch (Exception e) {
        message = "Could not upload the file: " + file.getOriginalFilename() + "!";
        return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
      }
    }

Service

    public FileDB store(MultipartFile file) throws IOException {
      String fileName = StringUtils.cleanPath(file.getOriginalFilename());
      FileDB FileDB = new FileDB(fileName, file.getContentType(), file.getBytes());
      return fileDBRepository.save(FileDB);
    }

Postman

Client

DB

PostgreSQL

Reactive

Controller

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Mono<Certificate> uploadFile(@RequestPart("file") Mono<FilePart> file) {
        return file.flatMap(this.service::store);
    }

Service

    public Mono<Certificate> store(FilePart file) {
        try {
            String fileName = StringUtils.cleanPath(file.filename());
            Certificate cert = new Certificate();
            // cert.setCertificate(file.getBytes());
            cert.setFileName(fileName);
            // cert.setFileType(file.getContentType());
            return repository.save(cert);
        } catch (Exception e) {
            return Mono.empty();
         }
    }

DB

Reactive

Question

The Reactive code allows me to store the file name but I'm unable to get the byte[] out of the FilePart.

Using MultiPart instead of FilePart will throw a application/PDF format not supported I tried to use a Flux instead of a Mono, or to use @RequestBody, @RequestPart without success.

Could someone tell me how to get a byte[] out of a FilePart without saving a file to the disk, or any other way to do it ?

Upvotes: 1

Views: 1030

Answers (0)

Related Questions