Home > Software engineering >  Display Image using Base64 GoLang Template
Display Image using Base64 GoLang Template

Time:09-17

I am trying to display image using Base 64 in GoLang. I've looked at various examples and everywhere its the same pattern. Here is my code:

{{template "base" .}}

{{define "content"}}
    {{$item := index .Data "item"}}
    {{$image := index .Data "image"}}
    
    <img src="data:image/png;base64,"   {{$image.ImageDataBase64}} alt="Blank"/>
    {{$image.ImageDataBase64}}
{{end}}

Note that I am first trying to show image using base64, and then I am printing base64 just to make sure everything is okay. And here is the result I am getting: enter image description here

So, it actually displays base64, but it does not display the image when I insert base64 in tag. Why?

Here is how I created base64:

package images

import (
    "bytes"
    "encoding/base64"
    "fmt"
    "image/jpeg"
    "image/png"
    "io/ioutil"
    "log"
    "net/http"
)

var TmpDirectory string // Temorary Directory where all images in current session wil be stored

func setupCorsResponse(w *http.ResponseWriter, r *http.Request) {
    (*w).Header().Set("Access-Control-Allow-Origin", "*")
    (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    (*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Authorization")
}

func HandleUpload(w http.ResponseWriter, r *http.Request, formFileName string) (string, string, error) {
    // Maximum upload of 10 MB files r.ParseMultipartForm(1 << 2)

    file, handler, err := r.FormFile(formFileName)
    if err != nil {
        // If there is an error that means form is empty. Return nil for err in order
        // to validate result as required.
        return "", "", nil
    }

    defer file.Close()

    fmt.Printf("Uploaded File: % v\n", handler.Filename)
    fmt.Printf("File Size: % v\n", handler.Size)
    fmt.Printf("MIME Header: % v\n", handler.Header)

    data, err := ioutil.ReadAll(file)
    if err != nil {
        log.Println(err)
        return "", "", err
    }

    contentType := http.DetectContentType(data)

    switch contentType {
    case "image/png":
        fmt.Println("Image type is already PNG.")
    case "image/jpeg":
        fmt.Println("Image type is JPG, converting it to PNG.")
        img, err := jpeg.Decode(bytes.NewReader(data))
        if err != nil {
            return "", "", fmt.Errorf("unable to decode jpeg: %w", err)
        }
        var buf bytes.Buffer

        if err := png.Encode(&buf, img); err != nil {
            return "", "", fmt.Errorf("unable to encode png")
        }
        data = buf.Bytes()
    default:
        return "", "", fmt.Errorf("unsupported content type: %s", contentType)
    }
    //convert the buffer bytes to base64 string - use buf.Bytes() for new image
    imgBase64Str := base64.StdEncoding.EncodeToString(data)
    return handler.Filename, imgBase64Str, nil
}

What am I doing wrong here?

CodePudding user response:

Blank is showing because your alt text for your failing image is Blank.

<img src="data:image/png;base64,"   {{$image.ImageDataBase64}} alt="Blank"/>

Given a value of "AAAA" your output from the template would be

<img src="data:image/png;base64,"   AAAA alt="Blank"/>

What you likely want requires a simple change:

<img src="data:image/png;base64,{{$image.ImageDataBase64}}" alt="Blank"/>

Which would produce

<img src="data:image/png;base64,AAAA" alt="Blank"/>

Remember, you aren't building a string (or concatenating with operator) you are just output the contents of the string.

  • Related