2016-12-15 45 views
1

我正在以png格式保存畫布圖像,並將其發送到我的服務器。我發送的字符串是這種格式...move_uploaded _file等於Go

data:image/png;base64,iVBORw0K... 

我想將此圖像保存到我的服務器上的圖像稱爲圖像文件夾。但是當我查找例子時,我找不到任何例子。我基本上想要做什麼move_uploaded_file將在PHP做。現在我有這個...

type test_struct struct { 
    Test string `json:"image"` 
} 

func GetImage(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) { 

    var img test_struct 
    json.NewDecoder(req.Body).Decode(&img) 

現在我將如何保存img.Test,這是字符串格式以上,到一個文件夾在我的服務器,這樣,當我打開該文件夾,我可以看到的形象呢?

回答

1

如果您已經有了一個以base64編碼的文件的字符串,您必須對其進行解碼並獲取[]byte數據,最後用它編寫一個文件。

position := strings.Index(img.Test, ",") 
if position == -1 { 
    // image format doesn't match with 'data:image/png;base64,iVBO...' 
} 
// decode the base64 string, removing 'data:image/png;base64,' from it 
reader := base64.NewDecoder(base64.StdEncoding, bytes.NewBufferString(img.Image[position+1:])) 

data, err := ioutil.ReadAll(reader) 
if err != nil { 
    // error handler 
} 
// you write the file in wherever you want 
ioutil.WriteFile("./image.png", data, 0644)