首页 > 解决方案 > 使用 Apache Commons 在 Groovy 中对图像文件进行 Base 64 编码

问题描述

我正在尝试使用此站点上的说明将图像文件编码为 Base64 字符串。唯一的区别是我有一个 groovy 脚本(而不是 Java),我的整个脚本只是....

  @Grapes(
    @Grab(group='commons-io', module='commons-io', version='2.6')
  )

 import org.apache.commons.io.FileUtils
 import org.apache.commons.codec.binary.Base64


  byte[] fileContent = FileUtils.readFileToByteArray(new File('/Users/me/Test.jpeg'));
  String encodedString = Base64.getEncoder().encodeToString(fileContent);

当我运行它时,我得到以下异常并且无法弄清楚为什么......

 groovy.lang.MissingMethodException: 
 No signature of method: static org.apache.commons.codec.binary.Base64.getEncoder() is applicable for argument types: () values: []
 Possible solutions: encode([B), encode(java.lang.Object)

标签: javagroovyencodingbase64apache-commons-codec

解决方案


您正在导入org.apache.commons.codec.binary.Base64.

随着Base64.getEncoder().encodeToString(fileContent)您的调用java.util.Base64,它具有除org.apache.commons.codec.binary.Base64.

由于java.util.*是 Groovy 的默认导入之一,因此您的代码在删除import org.apache.commons.codec.binary.Base64.


推荐阅读