Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 string decode and save as file

Tags:

file

base64

go

This has been doing my head in and I hope someone can help. Please forgive me if it's a stupid question as I am very new to Go.

I have a struct that has base64 in it. the struct looks like this:

 type UploadedFile struct {
    PartnerId string
    FileName string
    UploadDateTime string
    FileChecksum string
    FileBase64 string
 }

I want to take that base64 string, decode it and then save it, sounds simple right and it probably is, but I am struck.

The code looks like this:

decoder := json.NewDecoder(r.Body)
uploadedFile := models.UploadedFile{}
err := decoder.Decode(&uploadedFile)
dec, _ := base64.StdEncoding.DecodeString(uploadedFile.FileBase64)

Where do I go from here? I have tried so many things and I just keep getting errors all over the file.

I have tried adapting code that people use for images, but I always crash and burn as the file isn't an image, it could be anything

Thanks in advance.

like image 297
Paul A.T. Wilson Avatar asked Apr 04 '17 15:04

Paul A.T. Wilson


People also ask

How do I save a Base64 file?

How to convert Base64 to file. Paste your string in the “Base64” field. Press the “Decode Base64 to File” button. Click on the filename link to download the file.

How do I decode a Base64 encoded file?

To decode a file with contents that are base64 encoded, you simply provide the path of the file with the --decode flag. As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.


1 Answers

Update: I forgot to mention that, if you use f.Write make sure to also call f.Sync after you're done writing to ensure that all the contents you've written are actually stored. The example shows the updated code.

Not sure if your code example is incomplete, so this answer might be irrelevant but to save your decoded string bytes to a file you first need to open or create a file and then write the bytes into it. Something like this:

package main

import (
    "encoding/base64"
    "io"
    "os"
)

var b64 = `TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=`

func main() {
    dec, err := base64.StdEncoding.DecodeString(b64)
    if err != nil {
        panic(err)
    }

    f, err := os.Create("myfilename")
    if err != nil {
        panic(err)
    }
    defer f.Close()

    if _, err := f.Write(dec); err != nil {
        panic(err)
    }
    if err := f.Sync(); err != nil {
        panic(err)
    }
}

Run it here: https://play.golang.org/p/SZVquhZdXC

like image 170
mkopriva Avatar answered Nov 11 '22 19:11

mkopriva