Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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?

The idea is to pass it to a Spring InputStreamSource. I'm trying the method below, but it returns saying "the byte array does not contain a file name.".

MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);      
helper.setFrom("[email protected]", "xyz");
helper.setTo(email);
helper.setText(body,true);
helper.setSubject(subject);
helper.addInline("cImage",
        new InputStreamResource(new ByteArrayInputStream(imageByteArr)));

mailSender.send(message);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Can you paste the full stack trace? There is no such thing as an "in memory" file. Using a ByteArrayInputStream should be sufficient.


You need to implement Resource#getFilename(). Try the following:

helper.addInline("cImage", new ByteArrayResource(imageByteArr){
            @Override
            public String getFilename() {
                return fileName;
            }
        });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...