Camunda Cockpit获取PDF变量转邮件附件时Java类型转换问题
需求:获取上传的PDF类型执行变量proofOfRequestFile,通过Java服务任务将其作为邮件附件发送,该PDF的二进制数据实际存储在pdf变量中。
尝试1:强转为FileValue
FileValue pdfVariable = (FileValue) delegateExecution.getVariable("proofOfRequestFile");
返回错误:
class java.io.ByteArrayInputStream cannot be cast to class org.camunda.bpm.engine.variable.value.FileValue (java.io.ByteArrayInputStream is in module java.base of loader 'bootstrap'; org.camunda.bpm.engine.variable.value.FileValue is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @4f7d0008)
注:替换为(File)强转也返回相同错误
尝试2:强转为byte数组
byte[] pdfBytes = (byte[]) delegateExecution.getVariable("proofOfRequestFile");
返回错误:
class java.io.ByteArrayInputStream cannot be cast to class [B (java.io.ByteArrayInputStream and [B are in module java.base of loader 'bootstrap')
尝试3:使用pdf变量强转为byte数组
byte[] pdfBytes = (byte[]) execution.getVariable("pdf");
返回错误:
class java.lang.String cannot be cast to class [B (java.lang.String and [B are in module java.base of loader 'bootstrap')
解决方案
处理proofOfRequestFile变量(ByteArrayInputStream类型)
变量实际存储的是ByteArrayInputStream,需从流中读取字节数组:
ByteArrayInputStream pdfStream = (ByteArrayInputStream) delegateExecution.getVariable("proofOfRequestFile"); byte[] pdfBytes = new byte[pdfStream.available()]; pdfStream.read(pdfBytes); // 用pdfBytes构建邮件附件,例如通过JavaMail API添加附件
处理pdf变量(Base64编码字符串类型)
pdf变量存储的是Base64编码的字符串,需解码为byte数组:
import java.util.Base64; String pdfBase64Str = (String) execution.getVariable("pdf"); byte[] pdfBytes = Base64.getDecoder().decode(pdfBase64Str); // 后续用pdfBytes处理邮件附件
错误原因说明
- 尝试1/2失败:
proofOfRequestFile的实际类型是ByteArrayInputStream,并非FileValue/File/byte[],直接强转类型不匹配 - 尝试3失败:
pdf变量存储的是Base64编码的字符串,不是原始二进制数组,强转byte[]必然报错
内容的提问来源于stack exchange,提问作者b_a9f

