【问题标题】:How to embed images and attach files from spring boot resources folder如何从 Spring Boot 资源文件夹嵌入图像和附加文件
【发布时间】: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


    【解决方案1】:

    由于您的资源是 jar 容器的一部分,因此您不能使用文件路径,而是使用类加载器提供的 URL。根据您是从 IDE 启动它还是从部署的 jar 启动它,这将是 file://...jar:... URL。资源文件夹不是 spring boot 结构的一部分,所以你不能使用它。使用 URLDataSource 你可以这样做:

    URLDataSource source = new URLDataSource(this.getClass().getResource("/images/header.png"));
    

    【讨论】:

    • 很高兴听到 :-) 如果您将其标记为正确答案,那就太好了。
    • 我刚刚将答案标记为正确答案。再次感谢您。
    猜你喜欢
    • 2017-06-01
    • 2013-03-12
    • 2014-11-21
    • 2017-11-08
    • 2017-03-13
    • 2018-05-28
    • 2017-02-05
    • 1970-01-01
    • 2015-11-27
    相关资源
    最近更新 更多