- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
无法从 spring boot 资源文件夹中嵌入图像和附加文件
我使用 Spring Boot 创建了一个 Restful Web 服务(Jar 文件而不是 War 文件)。有些服务会发送电子邮件,有些服务会发送带附件的电子邮件(将动态创建)。 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
我尝试了以下方法,但没有成功
方法一
ServletContext context;
String path = context.getRealPath("/resources/images")+"/header.png";
它正在以下文件夹中查找图像,但该文件夹中没有图像。
C:\Users\username\AppData\Local\Temp\tomcat-docbase..\resources\images/header.png
方法二
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 jar 会在运行时爆炸吗?从 spring boot jar 文件加载图像的正确方法是什么。
最佳答案
由于您的资源是 jar 容器的一部分,因此您不能使用文件路径,而只能使用类加载器提供的 URL。根据您是从 IDE 还是部署的 jar 启动它,这将是一个 file://...
或 jar:...
URL。资源文件夹不是 spring boot 结构的一部分,所以你不能使用它。使用 URLDataSource 你可以这样做:
URLDataSource source = new URLDataSource(this.getClass().getResource("/images/header.png"));
关于rest - 如何从 spring boot 资源文件夹中嵌入图像和附加文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44105840/
我是一名优秀的程序员,十分优秀!