dongrao9436
2019-05-15 01:24
浏览 1.0k
已采纳

如何从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.

图片转代码服务由CSDN问答提供 功能建议

我想从字符串变量中获取原始文件的大小,该字符串变量是通过使用base64编码文件获得的。

  
 
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”)
 //如何从数据中获取文件大小
} 
   
 
 <  p>如何从数据获取文件大小?  ks。 
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dqs86517 2019-05-15 04:14
    已采纳

    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

    已采纳该答案
    打赏 评论
  • douba8819 2019-05-15 01:50

    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.

    1. OR you can calculate the file size using below formula:

    x = (n * (3/4)) - y Where:

    1. x is the size of a file in bytes
    2. n is the len(datas)
    3. y will be 2 if Base64 ends with '==' and 1 if Base64 ends with '='.
    打赏 评论

相关推荐 更多相似问题