Java-从字符串形式的字节下载PDF



我们正在调用一些API,它将字节作为字符串返回,我需要从该字节流(作为字符串(下载PDF。

例如

download_pdf":[{"name":"Transaction_Details.pdf","value":"JVBERi0xLjQNCiXi48/TDQoyIDAgb2JqCjw8L051bXNbMCAzIDAgUl..."}]

当试图从中写入文件时,它会被损坏,无法打开文件。

try {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" +item.getName())
.body(item.getValue().getBytes());
} catch (Exception e) {
e.printStackTrace();
}

尝试过下面的代码也没有成功。

InputStream inputStream = new ByteArrayInputStream(item.getValue().getBytes()(Charset.forName("UTF-8")));

如何从文件/字节(作为字符串(创建InputStream OR byte[]?

结构是API响应,它不归我们所有,因此在这方面无法提供帮助。但正如所建议的那样,在其中一条评论中谨慎地优化了Base64解码解决了问题。我接受他的回答,并补充为新的评论。

Base64 decoder = new Base64();
byte[] decodedBytes = decoder.decode(item.getValue());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, ATTACHMENT_FILENAME +item.getName())
.body(decodedBytes);```

最新更新