Create a Java File object (or equivalent) using a byte array in memory (without a physical file)

前端 未结 5 656
情深已故
情深已故 2020-12-15 12:38

I want to create a Java File object in memory (without creating a physical file) and populate its content with a byte array.

Can this be done?

T

5条回答
  •  爱一瞬间的悲伤
    2020-12-15 13:29

    Have you tried changing the resource you feed to addInline()? If you wanted the resource to be in memory, I would have tried a org.springframework.core.io.ByteArrayResource.

    Update: I think you might need to use the DataSource version of the addInline() method and then use a byte array bound data source object to feed the data into the helper class. I would try the following:

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message);              
    helper.setFrom("no-reply@example.com", "xyz");
    helper.setTo(email);
    helper.setText(body,true);
    helper.setSubject(subject);
    
    // use javax.mail.util.ByteArrayDataSource
    ByteArrayDataSource imgDS = new ByteArrayDataSource( imageByteArr, "image/png");
    helper.addInline("cImage", imgDS);
    
    mailSender.send(message);
    

提交回复
热议问题