How to convert an InputStream to a DataHandler?

后端 未结 7 751
挽巷
挽巷 2020-12-05 07:20

I\'m working on a java web application in which files will be stored in a database. Originally we retrieved files already in the DB by simply calling getBytes o

7条回答
  •  借酒劲吻你
    2020-12-05 07:32

    Here is an answer for specifically working with the Spring Boot org.springframework.core.io.Resource object which is I think how a lot of us are getting here. Note that you might need to modify the content type in the code below as I'm inserting a png file into an html formatted email.

    Note: As others have mentioned, merely attaching an InputStream isn't enough as it gets used multiple times, just mapping through to Resource.getInputStream() does the trick.

    public class SpringResourceDataSource implements DataSource {
        private Resource resource;
    
        public SpringResourceDataSource(Resource resource) {
            this.resource = resource;
        }
    
        @Override
        public InputStream getInputStream() throws IOException {
            return resource.getInputStream();
        }
    
        @Override
        public OutputStream getOutputStream() throws IOException {
            throw new UnsupportedOperationException("Not implemented");
        }
    
        @Override
        public String getContentType() {
            return "image/png";
        }
    
        @Override
        public String getName() {
            return "SpringResourceDataSource";
        }
    }   
    

    Usage of the class looks like this:

        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource logoImage = pathMatchingResourcePatternResolver.getResource("/static/images/logo.png");
        MimeBodyPart logoBodyPart = new MimeBodyPart();
        DataSource logoFileDataSource = new SpringResourceDataSource(logoImage);
    
    
        logoBodyPart.setDataHandler(new DataHandler(logoFileDataSource));
    

提交回复
热议问题