Warm tip: This article is reproduced from serverfault.com, please click

what is the best way to convert base64 to image and save it locally?

发布于 2020-11-29 07:24:04

From the client I receive the photo which is converted in base64, now I have to decode the base64 to image and save it in the local folder, how can I do it?

Questioner
Masud Morshed
Viewed
0
Brits 2020-11-29 16:14:32

this code doesn't work.

Your code won't compile; base64.NewDecoder returns an io.Reader; you cannot use []byte() to convert that into a byte slice (ioutil.ReadAll could do that for you). However there is no need to do this; you can copy the Reader to a file:

dec := base64.NewDecoder(base64.StdEncoding, strings.NewReader(photo[i+1:]))
f, err := os.Create("/var/www/upload/" + req.Title + ".png")
if err != nil {
    panic(err)
}
defer f.Close()
_, err = io.Copy(f, dec)
if err != nil {
    panic(err)
}