move_uploaded _file equivalent in Go

huangapple go评论72阅读模式
英文:

move_uploaded _file equivalent in Go

问题

我正在保存一个以 png 格式的画布图像,并将其发送到我的服务器。我发送的字符串格式如下:

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

我想将这个图像保存到服务器上名为 "images" 的文件夹中。但是当我寻找示例时,找不到任何相关的内容。基本上,我想做的就是在 PHPmove_uploaded_file 函数所做的事情。目前我有以下代码:

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(即上述字符串格式)保存到服务器上的文件夹中,以便在打开该文件夹时可以看到图像?

英文:

I am saving an canvas image in png format, and sending it to my server. The string I am sending is in this format...

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

I want to save this image to a folder called images on my server. But when I look for examples I can't find any. I basically want to do what move_uploaded_file would do in PHP. Right now I have this...

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)

Now how would I save img.Test, which is the string format above, to a folder in my server so that when I open that folder I can see the image?

答案1

得分: 1

如果你已经有一个使用base64编码的字符串,你需要对其进行解码并获取[]byte数据,最后将其写入文件。

position := strings.Index(img.Test, ",")
if position == -1 {
    // 图片格式与"data:image/png;base64,iVBO..."不匹配
}
// 解码base64字符串,从中删除"data:image/png;base64,"
reader := base64.NewDecoder(base64.StdEncoding, bytes.NewBufferString(img.Image[position+1:]))

data, err := ioutil.ReadAll(reader)
if err != nil {
    // 错误处理
}
// 将文件写入任何你想要的位置
ioutil.WriteFile("./image.png", data, 0644)
英文:

If you already have a string with the file encoded in base64, you must to decode it and get the []byte data, and finally write a file with it.

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)

huangapple
  • 本文由 发表于 2016年12月15日 12:51:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/41156640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定