java 从Sping Boot 中的BLOB返回Base64编码字符串?

zpjtge22  于 2023-01-04  发布在  Java
关注(0)|答案(2)|浏览(319)

我有一个LanguageController类,其中有这个方法:

@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);
    }
}

Language类是(省略了getter和setter,这样更简洁):

@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;
    }
}

在这里,当我使用API端点时,我得到了这个JSON:

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

在这里,我返回BLOB流,它不是非常有用。
我想返回用Base64编码的BLOB,但我真的不知道在哪里对文件进行编码。
谢谢你的帮忙!

8ftvxx2r

8ftvxx2r1#

您可以尝试在实体类的Blob字段上使用@JsonSerialize注解来影响blob的序列化方式。SqlBlobSerializer类似乎正在执行您所寻找的到base64的转换。

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

jgwigjjp2#

您可以返回LanguageDTO示例,而不是返回@Entity Language,DTO是从Language示例初始化的类,并且在其中将Blob转换为Base64。

相关问题