【发布时间】:2017-10-21 16:43:12
【问题描述】:
无法从 Spring Boot 资源文件夹嵌入图像和附加文件
我使用 Spring Boot(Jar 文件而不是 War 文件)创建了一个 Restful Web 服务。一些服务将发送电子邮件,其中一些将发送带有附件的电子邮件(将动态创建)。 Web 部件(Angular)驻留在部署在不同服务器中的 Apache 服务器中。
我正在使用 Freemarker 模板撰写电子邮件并使用 Amazon SES 发送电子邮件。
来自freemarker模板
<IMG src="cid:gridEmailHeaderImage">
添加图片的代码
MimeBodyPart inlineImage = new MimeBodyPart();
DataSource fds = new FileDataSource(imagePath.getAbsolutePath());
inlineImage.setDataHandler(new DataHandler(fds));
inlineImage.setHeader("Content-ID", "<" + contentId + ">");
inlineImage.setFileName(fds.getName());
content.addBodyPart(inlineImage);
如果我提供绝对路径,我可以嵌入和附加文件。但是,如果提供相对路径,它就不起作用。
我的文件夹结构
C:\workspace\service-1.0\src\main\resources\images\header.png
C:\workspace\service-1.0\src\main\resources\attachements\test-attachment-1.txt
我尝试了以下没有成功
方法 1
ServletContext context;
String path = context.getRealPath("/resources/images")+"/header.png";
它正在以下文件夹中查找图像,但该文件夹中没有图像。
C:\Users\username\AppData\Local\Temp\tomcat-docbase..\resources\images/header.png
方法 2
basePath = this.getClass().getClassLoader().getResource("/images/").getPath();
C:\workspace\service-1.0\src\main\resources\images\header.png
/C:/workspace/service-1.0/build/libs/service-1.0.jar!/BOOT-INF/classes!/images/ (仅适用于 Eclipse,但不适用于命令提示符 java -jar build\lib\myapp.jar)
方法 3
ClassPathResource file = new ClassPathResource("header.png");
String mypath = file.getFile().getAbsolutePath();
(这也没用)
如果我将图像放在资源下的图像文件夹中。我可以通过以下 URL 查看图像。
http://localhost:7075/myservice/v1/images/header.png
可以从资源文件夹加载图像吗? spring boot jars 会在运行时爆炸吗?从spring boot jar文件加载图像的正确方法是什么。
【问题讨论】:
标签: rest spring-boot resources microservices amazon-ses