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?
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)
}
Thanks, it's worked. brother do you know how to find the image extension from the base64? It will be great if I find the extension I will save the image with the extension, in the above code I just used static 'png' extension to save the image.
@MasudMorshed you can find out the datatype based on the header of the type, see here and here
@MasudMorshed btw. the image in your example is a jpg, not png. I updated the linked answer in the second link.