我们正在做同样的事情,基本上将PDF作为JSON发送到Android/iOS和Web客户端(因此涉及Java和Swift)。
JSON对象:
public class Attachment implements Serializable {
private String name;
private String content;
private Type contentType; // enum: PDF, RTF, CSV, ...
// Getters and Setters
}
然后从字节数组 content 中以以下方式设置:
public Attachment createAttachment(byte[] content, String name, Type contentType) {
Attachment attachment = new Attachment();
attachment.setContentType(contentType);
attachment.setName(name);
attachment.setContent(new String(Base64.getMimeEncoder().encode(content), StandardCharsets.UTF_8));
}
在客户端Java中,我们需要先创建自己的文件类型对象,然后再映射到java.io.File:
public OurFile getAsFile(String content, String name, Type contentType) {
OurFile file = new OurFile();
file.setContentType(contentType);
file.setName(name);
file.setContent(Base64.getMimeDecoder().decode(content.getBytes(StandardCharsets.UTF_8)));
return file;
}
最后:
public class OurFile {
//...
public File getFile() {
if (content == null) {
return null;
}
try {
File tempDir = Files.createTempDir();
File tmpFile = new File(tempDir, name + contentType.getFileEnding());
tempDir.deleteOnExit();
FileUtils.copyInputStreamToFile(new ByteArrayInputStream(content), tmpFile);
return tmpFile;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
所以我尝试在本地进行编码和解码,它可以正常工作,因此问题可能是rest api传输数据的方式。
File inputFile = new File("some pdf"); String base64EncodedData = Base64.encodeBase64String(loadFileAsBytesArray(partiaFile)); //decode data File decodedFile = new File("some other pdf"); byte[] decodedBytes = Base64.decodeBase64(base64EncodedData); writeByteArraysToFile(decodedFile, decodedBytes); - rasty