if (attachment == null) {
return null;
}
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 1. 序列化
// 2. 压缩
Deflater def = new Deflater(Deflater.BEST_COMPRESSION, false);
DeflaterOutputStream dos = new DeflaterOutputStream(baos, def);
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(dos);
oos.writeObject(attachment);
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
}
}
def.end();
}
byte[] plaintext = baos.toByteArray().toByteArray();
// 3. base64编码
return StringEscapeUtil.escapeURL(new String(Base64.encodeBase64(plaintext, false), "ISO-8859-1"));
} catch (Exception e) {
log.error("Failed to encode field attachment", e);