简体   繁体   English

Base64字符串解码并另存为文件

[英]Base64 string decode and save as file

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. 如果这是一个愚蠢的问题,请原谅我,因为我是Go的新手。

I have a struct that has base64 in it. 我有一个结构,其中包含base64。 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. 我想取这个base64字符串,解码它然后保存它,听起来很简单,它可能是,但我很震惊。

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. 提前致谢。

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. 更新 :我忘了提一下,如果你使用f.Write,请确保在写完之后再调用f.Sync ,以确保实际存储了你编写的所有内容。 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 在这里运行: https//play.golang.org/p/SZVquhZdXC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM