Thymeleaf 在 Spring Boot 应用程序中不显示来自 base64 字符串的图像

问题描述 投票:0回答:1

我有一个 Spring Boot 应用程序,我使用 Thymeleaf 在前端显示作为 base64 字符串接收的图像。然而,尽管将base64字符串传递给Thymeleaf,图像并没有被显示。并且这个thymeleaf模板是通过邮件发送的

这是我的代码的简化版本:

1.我有一个“TaskDto”类,其中包含“byte[]”类型的字段“assignedToLogo”和作为“base64”表示形式的相应字段“assignedToLogoString”。

@Data

    @EqualsAndHashCode(callSuper = false)

    public class TaskDto extends BaseDto {

    private byte[] assignedToLogo;
    private String assignedToLogoString;
    private String assignedToName;
    }

2.我正在使用 Thymeleaf 迭代任务列表(今日项目)并尝试显示关联的图像:

<!-- Thymeleaf template in HTML -->
    <div th:each="item : ${todayitems}">
    <span>
    <img th:src="${item.assignedToLogoString}" style="height: 25px;">
    <span style="margin-left: 4px;">
    <span th:text="${item.assignedToName}"></span>
    </span>
    </span>
    </div>

3.“convert”方法将“assignedToLogo”从“byte[]”转换为“base64”字符串:

@Service

public class EmailGeneratorService {

@Value("${send.notification.mail.template.name1}")
private String SEND_NOTIFICATION_TEMPLATE_NAME;

@Autowired
private ProjectClient projectClient;

@Autowired
private ResourceLoader resourceLoader;

@Autowired
private JavaMailSender javaMailSender;

@Autowired
private TemplateEngine templateEngine;

public void sendMailTemplate(UserDto userDto) {
    Mail emailRequest = new Mail();
    String[] email = new String[] { userDto.getEmail() };
    emailRequest.setTo(email);
    emailRequest.setSubject("Test Email");
    emailRequest.setContent("This is the content of the email. You can use HTML if needed.");

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    
    ResponseEntity<ApiResponse> res = projectClient.getTodaysTaskFromAllProjectsForMail(Utils.getLongValueFromEncryptedString(userDto.getId()),
            userDto.getRole().name());
    List<TaskDto> allTasksOfToday = mapper.convertValue(res.getBody().getData(), new TypeReference<List<TaskDto>>() {});
    List<TaskDto> todaysTask = convert(allTasksOfToday);

    try {
        javax.mail.internet.MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,
                MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, StandardCharsets.UTF_8.name());

        // Thymeleaf template processing
        Context context = initializeThymeleafContext(emailRequest,todaysTask);

        String emailTemplate = templateEngine.process(SEND_NOTIFICATION_TEMPLATE_NAME, context);
        mimeMessageHelper.setText(emailTemplate, true);
        javaMailSender.send(mimeMessage);
        } catch (Exception e) {
        throw new RuntimeException("Failed to send email: " + e.getMessage());
    }

}

private Context initializeThymeleafContext(Mail emailRequest,List<TaskDto> todaysTask) {
    Context context = new Context();
    context.setVariable("emailContent", emailRequest.getContent());
    context.setVariable("todayitems", todaysTask);
    return context;
}

private static List<TaskDto> convert(List<TaskDto> taskDtos) {
    
    for (TaskDto task : taskDtos) {

        //task.getAssignedToLogo is in byte form.
        String base64Logo = Base64.getEncoder().encodeToString(task.getAssignedToLogo());
        System.out.println(base64Logo);
        task.setAssignedToLogoString(base64Logo);
    }
    return taskDtos;
}

问题:

尽管实现了signedToLogo 到base64 字符串的转换并将其传递给Thymeleaf,但图像并未显示在前端。

其他背景:

我已验证 Base64 字符串是否已正确生成。 浏览器控制台中没有错误。 我使用 Thymeleaf 和 Spring Boot 进行模板渲染。

问题:

有人可以帮我找出代码中的问题或提供有关如何排查和解决此问题的建议吗?我是否在 Thymeleaf 模板或 Java 代码中遗漏了某些内容?

如有任何帮助,我们将不胜感激!

java spring email thymeleaf
1个回答
0
投票

请确保您的 signedLogoToString 具有 "data:image/jpg;base64," 前缀。如果没有,请将其添加到您的 Java 代码中,

task.setAssignedToLogoString("data:image/jpg;base64,"+base64Logo);

或者您可以将其添加到您的 thymeleaf 模板中:

<img th:src="data:image/jpg;base64,${item.assignedToLogoString}" style="height: 25px;">

我更喜欢将其添加到 thymeleaf 模板中。

© www.soinside.com 2019 - 2024. All rights reserved.