Home > Net >  Return Base64 encoded string from BLOB in Spring Boot?
Return Base64 encoded string from BLOB in Spring Boot?

Time:01-03

So I have my LanguageController class in which I have this method:

@GetMapping("/languages")
public ResponseEntity<List<Language>> getAllLanguages(@RequestParam(required = false) String name) {
    try {
        List<Language> languages = new ArrayList<Language>();

        if (name == null) {
            languageRepository.findAll().forEach(languages::add);
        } else {
            languageRepository.findByNameContaining(name).forEach(languages::add);
        }

        if (languages.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }

        return new ResponseEntity<>(languages, HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

And the Language class is (omitted the getters and setters so it's cleaner):

@Entity
@Table(name = "languages")
public class Language {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "name")
    private String name;

    @Column(name = "audio")
    @Lob
    private Blob audio;

    @Column(name = "script")
    @Lob
    private Blob script;

    public Language() {

    }

    public Language(String name, Blob audio, Blob script) {
        this.name = name;
        this.audio = audio;
        this.script = script;
    }
}

And here when I consume the API endpoint, I get this JSON:

[
  {
    "id": 1,
    "name": "Test Language",
    "audio": {
      "binaryStream": {},
      "wrappedBlob": {
        "binaryStream": {},
        "traceId": 26,
        "traceObjectName": "blob26"
      }
    },
    "script": {
      "binaryStream": {},
      "wrappedBlob": {
        "binaryStream": {},
        "traceId": 27,
        "traceObjectName": "blob27"
      }
    }
  }
]

And here I'm returning the BLOB stream, which isn't super useful.

I would like to return the BLOB encoded in Base64, and I just genuinely don't know where to encode the files.

Thanks for your help!

CodePudding user response:

Instead of returning the @Entity Language you could return a LanguageDTO instance, the DTO being a class you initialize from the Language instance and in which you convert the Blob in Base64.

CodePudding user response:

You might try to use a @JsonSerialize annotation on the Blob fields of your entity class to influence how the blobs are serialized. The SqlBlobSerializer class seems to be doing the conversion to base64 you are looking for.

@Column(name = "audio")
@Lob
@JsonSerialize(using = SqlBlobSerializer.class) 
private Blob audio;
  • Related