如何从base64编码字符串获取原始文件大小
问题描述:
I want to get size of the original file from a string variable, which is obtained by using a base64 encode file.
package main
import (
"bufio"
"encoding/base64"
"io/ioutil"
"os"
)
func encodeFile(file string) string {
f, err := os.Open(file)
if err != nil {
panic(err)
}
reader := bufio.NewReader(f)
content, _ := ioutil.ReadAll(reader)
encoded := base64.StdEncoding.EncodeToString(content)
return encoded
}
func main() {
datas := encodeFile("/tmp/hello.json")
//how to get file size from datas
}
how to get the file size from datas? thks.
我想从字符串变量中获取原始文件的大小,该字符串变量是通过使用base64编码文件获得的。 p>
package main
import(
“ bufio”
“ encoding / base64”
“ io / ioutil“
” os“
)
func encodeFile(文件字符串)字符串{
f,err:= os.Open(file)
如果err!= nil {
panic(err)
}
读者:= bufio.NewReader(f)
内容,_:= ioutil.ReadAll(reader)
编码:= base64.StdEncoding.EncodeToString(content)
返回已编码
}
\ nfunc main(){
datas:= encodeFile(“ / tmp / hello.json”)
//如何从数据中获取文件大小
}
code> pre>
如何从数据 code>获取文件大小? ks。 p>
div>
答
This should do it:
func calcOrigBinaryLength(datas string) int {
l := len(datas)
// count how many trailing '=' there are (if any)
eq := 0
if l >= 2 {
if datas[l-1] == '=' {
eq++
}
if datas[l-2] == '=' {
eq++
}
l -= eq
}
// basically:
//
// eq == 0 : bits-wasted = 0
// eq == 1 : bits-wasted = 2
// eq == 2 : bits-wasted = 4
// each base64 character = 6 bits
// so orig length == (l*6 - eq*2) / 8
return (l*3 - eq) / 4
}
Playground validation: https://play.golang.org/p/Y4v102k74V5
答
Well, base64 encoded string has different length then original file. To get original size you can do next:
1. In function encodeFile return len(content) which is size of original file.
- OR you can calculate the file size using below formula:
x = (n * (3/4)) - y Where:
- x is the size of a file in bytes
- n is the
len(datas) - y will be 2 if Base64 ends with '==' and 1 if Base64 ends with '='.