答案 0 :(得分:5)
实现这一目标的一种方法是:
DataSource ds = new ByteArrayDataSource(getServletContext().getResourceAsStream("WEB-INF/resources/images/logomailtemplate.png") ,mimeType);
getServletContext().getResourceAsStream()
是从HttpServlet
收到并返回InputStream
。
最好还是这样做
String fileName = "/WEB-INF/resources/images/logomailtemplate.png";
InputStream stream = getServletContext().getResourceAsStream(fileName); //or null if you can't obtain a ServletContext
if (stream == null) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = this.getClass().getClassLoader();
}
stream = classLoader.getResourceAsStream(fileName);
}
DataSource ds = new ByteArrayDataSource(stream, "image/*");
<强>更新强>
可选地
String fileName = "WEB-INF/resources/images/logomailtemplate.png";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = this.getClass().getClassLoader();
}
DataSource ds = new FileDataSource(new File(classLoader.getResource(fileName).toURI()));
//OR
DataSource ds = new URLDataSource(classLoader.getResource(fileName));
确保fileName
以“/".