Java Mail Base64编码的图像附件字符串 [英] java mail Base64 encoded string to image attachment
问题描述
我有一个base64编码的字符串,该字符串使用JSON发布到Spring表单中.
I have a base64 encoded string which is posted using JSON into a Spring form.
data:image/png;base64,iVBORw0KGg......etc
我想将此图像添加为电子邮件的附件.附加文件可以很好地工作,但是只是将base64字符串添加为附件.
I want to add this image as an attachment to an email. Attaching the file works fine, but it is just adding the base64 string as the attachment.
我正在使用以下代码创建附件部分.
I am using the following code to create the attachment part.
private MimeBodyPart addAttachment(final String fileName, final String fileContent) throws MessagingException {
if (fileName == null || fileContent == null) {
return null;
}
LOG.debug("addAttachment()");
MimeBodyPart filePart = new MimeBodyPart();
String data = fileContent;
DataSource ds;
ds = new ByteArrayDataSource(data.getBytes(), "image/*");
// "image/*"
filePart.setDataHandler(new DataHandler(ds));
filePart.setFileName(fileName);
LOG.debug("addAttachment success !");
return filePart;
}
我也尝试过
ds = new ByteArrayDataSource(data, "image/*");
如何使用ByteArrayDataSource将base64字符串转换为正确的图像文件?
How can I convert the base64 string into a proper image file using the ByteArrayDataSource ?
推荐答案
您将必须首先使用Base64解码器.使用Java 8,您可以做到:
You'll hav to use a Base64-decoder first. With Java 8 you could do:
byte[] imgBytes = Base64.getDecoder().decode(base64String);
使用较旧的Java版本,您将不得不使用apache commons-codec之类的库-周围有很多这样的库.
With older java-versions you'll have to use some library like apache commons-codec or something - there's lots of those around.
这篇关于Java Mail Base64编码的图像附件字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!