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?
Asked
Active
Viewed 219 times
-3
-
1*this code doesn't work.* - if you show code that doesn't work, makes sure to always include an exact description of the problem, what errors or exceptions you get or what unexpected output you get. Just writing *this code doesn't work* often leads to downvotes and the question might even get closed as "needs debugging details". – jps Nov 29 '20 at 09:21
-
"doesn't work" is not a problem description. HOW does it not work? What error or other unexpected behavior do you observe? – Jonathan Hall Nov 29 '20 at 09:30
1 Answers
1
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)
}

Brits
- 14,829
- 2
- 18
- 31
-
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. – Masud Morshed Nov 29 '20 at 08:38
-
1@MasudMorshed you can find out the datatype based on the header of the type, see [here](https://stackoverflow.com/questions/60186924/python-is-base64-data-a-valid-image/60188667#60188667) and [here](https://stackoverflow.com/questions/62329321/how-can-i-check-a-base64-string-is-a-filewhat-type-or-not/62330081#62330081) – jps Nov 29 '20 at 09:29
-
@MasudMorshed btw. the image in your example is a jpg, not png. I updated the linked answer in the second link. – jps Nov 29 '20 at 10:28