Java保存Rest API返回的application/octet-stream图片文件失败问题
PDI中User-Modified Java Class步骤保存octet-stream文件完整性问题
我正在使用Pentaho Data Integration(PDI)的「User-Modified Java Class」步骤,将Rest API返回的octet-stream保存到磁盘。我有针对Blob类型输入的可用示例,但始终无法完整保留原始文件的完整性,无法将octet-stream原样保存到磁盘。
目前我能成功将文件保存到磁盘,但生成的文件大小比原文件小约1k,尝试以.jpg扩展名打开时,图片查看器提示「不支持的文件类型」。
当前使用的代码
import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { Object[] r = getRow(); if (r == null) { setOutputDone(); return false; } String filename = get(Fields.In, "imageFile").getString(r); File f = new File(filename); FileOutputStream fos = null; BufferedOutputStream bos = null; try{ if (!f.exists()){ f.createNewFile(); } fos = new FileOutputStream(f); bos = new BufferedOutputStream(fos); // 我一直在调整这行代码... byte[] blobBytes = (byte[])get(Fields.In, "attachment").getBinary(r); bos.write( blobBytes ); bos.flush(); bos.close(); } catch(IOException e){} return true; }
注:代码片段get(Fields.In, "attachment")用于获取作为原始数据的octet-stream(即Rest API响应的正文内容),该内容已被读取到PDI步骤中。
已尝试的写法
我尝试了以下几种写法,结果完全一致:
写法1:
byte[] blobBytes = (byte[])get(Fields.In, "attachment").getBinary(r);
写法2:
byte[] blobBytes = get(Fields.In, "attachment").getBinary(r);
直接写入输出流的写法3:
bos.write( (byte[])get(Fields.In, "attachment").getBinary(r) );
直接写入输出流的写法4:
bos.write( get(Fields.In, "attachment").getBinary(r) );
每种方式生成的文件大小均为13k,且图片查看器均提示「不支持的文件类型」。
Rest API响应头信息
{"Status":"200", "Transfer-Encoding":"chunked", "X-AR-TR-Core-Id":"bF1KNClCSZe6ocXTD2vdlQ", "X-AR-TR-Counter":"1", "X-Content-Type-Options":"nosniff", "Date":"Wed, 03 Apr 2024 02:48:19 GMT", "X-Frame-Options":"SAMEORIGIN", "Strict-Transport-Security":"max-age=31622400; includeSubDomains", "Cache-Control":"no-store", "Content-Security-Policy":"frame-ancestors 'self'", "Content-Disposition":"attachment ;filename=CA-1N CB F504168.jpg", "Set-Cookie":"_cacheId=279713", "Vary":"Accept-Encoding, User-Agent", "Expires":"Thu, 01 Jan 1970 00:00:00 GMT", "X-XSS-Protection":"1; mode=block", "Content-Type":"application/octet-stream"}
我的Java技术水平有限,恳请各位提供解决方案。
内容的提问来源于stack exchange,提问作者Ezra Wise
相关产品推荐
相关产品推荐

