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
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));