我正在使用Angular從Rest調用發送base64字符串到Golang服務器。現在的問題是使用此字符串創建圖像。如何使用golang在文件系統中從base64字符串創建jpg/png圖像
我的代碼:
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
}
請你的代碼添加到的問題 – Jadeye
可能的複製【如何寫一個base64解碼PNG圖像文件? ](http://stackoverflow.com/questions/33149551/how-to-write-a-base64-decoded-png-image-to-file/33149620#33149620);和[去base64圖像解碼](http://stackoverflow.com/questions/33319759/go-base64-image-decode/33321592#33321592)。 – icza