You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Groovy脚本无法将Base64内容保存为指定文件的问题求助

解决Groovy代码无法将Base64接口响应保存为PDF文件的问题

原代码的潜在问题

  • 文件路径替换时,.是正则表达式通配符,未转义会导致意外替换(比如a.txt.bak会被改成a_42PP.pdf.bak),不符合预期
  • Base64解码逻辑冗余:直接解码Base64字符串即可,无需先转成字节数组再解码
  • 缺少异常捕获,出现错误时无法定位具体原因(比如路径不存在、Base64格式错误)
  • 手动管理流资源容易遗漏关闭,可能导致文件损坏

修正后的代码

import org.apache.commons.codec.binary.Base64
import com.eviware.soapui.support.GroovyUtils

// 获取项目属性中的原始文件路径
def file_path = testRunner.testCase.testSuite.project.getPropertyValue("xml_file")
log.info("原始文件路径: " + file_path)
// 转义点号并匹配字符串结尾,确保只替换txt后缀
file_path = file_path.replaceAll('\\.txt$','_42PP.pdf')
log.info("目标PDF路径: " + file_path)

def targetFile = new File(file_path)
// 自动创建不存在的父目录,避免路径错误
targetFile.parentFile.mkdirs()

try {
    // 解析接口响应XML
    def groovyUtils = new GroovyUtils(context)
    def holder = groovyUtils.getXmlHolder('publishAndReturnDocument#Response')
    holder.declareNamespace('ns1','http://www.documentrequester.com/schemas/')
    // 提取Base64字符串
    def base64Str = holder.getNodeValue("//ns1:publishAndReturnDocumentResponse/publishAndReturnDocumentReturn")
    
    if (!base64Str) {
        log.error("接口返回的Base64内容为空")
        return
    }

    // 直接解码Base64字符串为PDF字节数组
    def pdfBytes = Base64.decodeBase64(base64Str)
    
    // 使用Groovy自动关流语法,无需手动flush/close
    targetFile.withOutputStream { fos ->
        fos.write(pdfBytes)
    }
    
    log.info("PDF文件已成功写入: " + file_path)
    testRunner.testCase.setPropertyValue("myFileStuff", "")
} catch (Exception e) {
    log.error("保存PDF文件失败: " + e.message, e)
    throw e // 抛出异常让SoapUI捕获,方便排查问题
}

关键修改说明

  1. 路径处理:用\\.txt$精准匹配结尾的txt后缀,避免正则意外替换
  2. 目录预检查:添加targetFile.parentFile.mkdirs()自动创建缺失的父目录
  3. 解码优化:直接调用Base64.decodeBase64解码字符串,去掉冗余的字节数组转换
  4. 资源自动管理:withOutputStream语法会自动关闭流,避免资源泄漏
  5. 异常与空值处理:捕获异常并打印详细日志,提前检查Base64字符串是否为空,减少无效操作

内容的提问来源于stack exchange,提问作者Yogesh Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 05:25:03