我使用Angular从Rest调用发送base64字符串到Golang服务器。现在的问题是使用这个字符串创建图像。
我的代码:
func (server *Server) uploadImage(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
defer r.Body.Close()
var d model.ImageFile
err := decoder.Decode(&d)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Println(d.Source)
fmt.Println(d.Destination)
fmt.Println(d.Country)
dir, errr := filepath.Abs(filepath.Dir(os.Args[0]))
if errr != nil {
fmt.Println(errr)
}
substring := dir[0:(len(dir) - 10)]
unbased, err := base64.StdEncoding.DecodeString(d.ImageData)
if err != nil {
fmt.Println("Cannot decode b64")
}
r = bytes.NewReader(unbased)
im, err := png.Decode(r)
if err != nil {
fmt.Println("Bad png")
}
f, err := os.OpenFile(substring+"images/"+"example.png", os.O_WRONLY|os.O_CREATE, 777)
if err != nil {
fmt.Println("Cannot open file")
}
png.Encode(f, im)
server.R.Text(w, http.StatusOK, d.ID.Hex())
return
}
答案 0 :(得分:5)
我会做这样的事情:
b := getB64PNG()
unbased, err := base64.StdEncoding.DecodeString(b)
if err != nil {
panic("Cannot decode b64")
}
r := bytes.NewReader(unbased)
im, err := png.Decode(r)
if err != nil {
panic("Bad png")
}
f, err := os.OpenFile("example.png", os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
panic("Cannot open file")
}
png.Encode(f, im)