mulesoft runtime: 4.3.0
數(shù)據(jù)庫存儲的是 BLOB 二進制文件∨古睿現(xiàn)在要通過 json 形式從 mulesoft api 中獲取。實現(xiàn)思路是將二進制轉(zhuǎn)換成 base64 字符串進行傳輸兜辞,最終通過 decode 的方式獲取二進制文件史简。
image.png
一邓线、先新建一個 java 類:
image.png
public class BinaryUtils {
/**
* Binary transform Base64 String.
* @param binary Binary input, received as a byte array.
* @return Base64 String by transcoding
*/
public static String binary2Base64String(byte[] binary) {
if (binary != null) {
byte[] encode = Base64.getEncoder().encode(binary);
return new String(encode);
}
return null;
}
}
二辜贵、添加 Transform Message 組件,并調(diào)用 java 方法:
image.png
%dw 2.0
output application/json
// 第一步導入 java 類
import java!net::hkbn::utils::BinaryUtils
---
{
"pdf": {
"commonHeader": {
"sourceId": vars.sourceId,
"trackingId": vars.trackingId,
"correlationId": vars.correlationId,
"code": "0"
},
"messagePayload": {
"code": 200,
"data": {
// 調(diào)用方法,傳遞參數(shù)為數(shù)據(jù)庫中的 blob 字段挺峡,注意該方法必須是靜態(tài)的葵孤。方法返回值可以是任意類型。
"pdf": BinaryUtils::binary2Base64String(payload[0].PDF_FILE)
}
}
}
}
postman 測試:
image.png
三橱赠、decode 一下就能輸出為文件
byte[] decode = Base64.decode(base64String.getBytes());
OutputStream os = new FileOutputStream("D:\\test\\1.pdf");
os.write(decode, 0, decode.length);
os.close();
image.png