2016-12-15 84 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)