【问题标题】:Can't display Base64 image in ReactJS from Spring Boot?无法从 Spring Boot 在 ReactJS 中显示 Base64 图像?
【发布时间】:2021-07-06 17:04:11
【问题描述】:

我试图在 react 中显示一个 base 64 编码的图像,它没有在网页上显示图像,它只显示一个轮廓。我将如何显示图像?

Spring Boot 后端

public void addNewBlog(String title, String description, String body, String author, MultipartFile image) throws IOException {
    String fileName = StringUtils.cleanPath(image.getOriginalFilename());
    Blog blog = new Blog(title, "", description, body, author);
    blog.setName(fileName);
    if(fileName.contains(".."))
    {
        System.out.println("not a valid file");
    }
    try {
        blog.setContent(Base64.getEncoder().encodeToString(image.getBytes()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    blog.setSize(image.getSize());
    blog.setUploadTime(new Date());

    blogRepository.save(blog);
}

图片

<img src={`data:image/jpeg;base64,${blog.content}`} style={{width: 100, height: 100 }} />

【问题讨论】:

  • src 属性在元素检查器中是否包含blog.content 值?
  • @TheHeadRush 是的。

标签: java reactjs spring spring-boot spring-mvc


【解决方案1】:

尝试将“jpg”更改为“jpeg”

img src={`data:image/jpeg;base64,${blog.content}`}...

你可以像这篇文章一样尝试检查base64的前后端字符集

https://stackoverflow.com/a/8499679/12234914

【讨论】:

  • 源码语法正确,不需要引号。并且图像的真实类型是正确的,我正在尝试显示 jpeg 图像。
  • 尝试将“jpg”改为“jpeg”
  • 仍然不显示图像。我想知道它是否与base64编码的字符串有关?或者我的浏览器,我使用的是谷歌浏览器。这很奇怪,因为一切看起来都正确。
  • 你可以看这篇文章,他们在说correct encoding from backend and frontend...stackoverflow.com/a/8499679/12234914
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 2021-03-04
相关资源
最近更新 更多