英文:
Display Image using Base64 GoLang Template
问题
我正在尝试在GoLang中使用Base64显示图像。我查看了各种示例,无论在哪里,都是相同的模式。这是我的代码:
{{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}}
请注意,我首先尝试使用base64显示图像,然后打印base64以确保一切正常。这是我得到的结果:
所以,它实际上显示了base64,但是当我将base64插入到<img/>
标签中时,它不显示图像。为什么?
这是我创建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
}
我在这里做错了什么?
英文:
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:
So, it actually displays base64, but it does not display the image when I insert base64 in <img/> 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?
答案1
得分: 1
"Blank"显示是因为您失败的图像的alt
文本为"Blank"。
<img src="data:image/png;base64,{{$image.ImageDataBase64}}" alt="Blank"/>
给定值"AAAA",您从模板中得到的输出将是:
<img src="data:image/png;base64,AAAA" alt="Blank"/>
您可能需要进行简单的更改:
<img src="data:image/png;base64,{{$image.ImageDataBase64}}" alt="Blank"/>
这将产生:
<img src="data:image/png;base64,AAAA" alt="Blank"/>
请记住,您不是在构建字符串(或使用+
运算符进行连接),而是只输出字符串的内容。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论