将 *multipart.FileHeader 的内容读入 []byte

Ale*_*lex 5 byte file go

如何将 *multipart.FileHeader 中包含的文件的正文/内容读取到 GO 中的字节片 ([]byte) 中。

我唯一需要做的就是将内容读入一个巨大的字节片中,但当然我想要文件的确切大小。我想之后用 md5 对文件内容进行哈希处理。

// file is a *multipart.FileHeader gotten from http request.
fileContent, _ := file.Open()
var byteContainer []byte
byteContainer = make([]byte, 1000000)
fileContent.Read(byteContainer)
fmt.Println(byteContainer)
Run Code Online (Sandbox Code Playgroud)

Ker*_*rem 5

尝试ioutil.ReadAll

https://play.golang.org/p/FUgPAZ9w2X

在你的情况下这样做;

byteContainer, err := ioutil.ReadAll(fileContent) // you may want to handle the error
fmt.Printf("size:%d", len(byteContainer))
Run Code Online (Sandbox Code Playgroud)

您可能还想从multipart 包文档中查看此示例, https://play.golang.org/p/084tWn65-d

  • 效果完美!谢谢 !长名字,我同意。:) 我花了太多时间来弄清楚如何正确读取该文件。 (2认同)