1

I am trying to display a base 64 encoded image in react and it is not displaying the image on the webpage, it only shows up with an outline. How would I go about displaying the image?

Spring Boot backend

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);
}

Image

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

1 Answers1

0

Try change "jpg" to "jpeg"

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

You can try check front and backend characterset of base64 like this article

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

  • The syntax of the source is correct, you don't need quotation marks. And the real type of the image is correct, I am trying to display a jpeg image. – MPagan Jul 07 '21 at 00:25
  • Try change the "jpg" to "jpeg" – Alan Ferreira Jul 07 '21 at 11:09
  • Still doesn't show the image. I'm wondering if it has something to do with the base64 encoded string? Or my browser, I am using Google Chrome. It's weird since everything looks right. – MPagan Jul 07 '21 at 14:52
  • You can see this article, their are saying about `correct encoding from backend and frontend`... https://stackoverflow.com/a/8499679/12234914 – Alan Ferreira Jul 07 '21 at 15:42