Encoding as Base64 in Java

前端 未结 17 2470
失恋的感觉
失恋的感觉 2020-11-21 13:44

I need to encode some data in the Base64 encoding in Java. How do I do that? What is the name of the class that provides a Base64 encoder?


I tried to use the <

17条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 13:53

    public String convertImageToBase64(String filePath) {
        byte[] fileContent = new byte[0];
        String base64encoded = null;
        try {
            fileContent = FileUtils.readFileToByteArray(new File(filePath));
        } catch (IOException e) {
            log.error("Error reading file: {}", filePath);
        }
        try {
            base64encoded = Base64.getEncoder().encodeToString(fileContent);
        } catch (Exception e) {
            log.error("Error encoding the image to base64", e);
        }
        return base64encoded;
    }
    

提交回复
热议问题