java mail Base64 encoded string to image attachment

后端 未结 5 2050
旧巷少年郎
旧巷少年郎 2020-12-21 08:38

I have a base64 encoded string which is posted using JSON into a Spring form.

data:image/png;base64,iVBORw0KGg......etc

I want to add this

5条回答
  •  天命终不由人
    2020-12-21 09:24

    With the answer of @jmehrens I was able to attach a file, but they couldn't be opened. Turned out you need to set the datatype seperately and remove it from the given fileContent String:

    {
       String dataType = StringUtils.substringBetween(file, "data:", ";base64,"); // extract data type (dataType = "image/png") 
    base64EncodedFileContent = fileContent.replaceFirst("data:.*;base64,", ""); // remove prefix from fileContent String (base64EncodedFileContent = "iVBORw0KGg......etc"
    
        MimeBodyPart filePart = new PreencodedMimeBodyPart("base64");
        filePart.setContent(base64EncodedFileContent, dataType);
        filePart.setFileName(fileName);
    
        return filePart;
     }
    

提交回复
热议问题