Search code examples
filegobyte

Read content of *multipart.FileHeader into []byte


How can I read the body/content of a file contained in a *multipart.FileHeader into a slice of bytes ([]byte) in GO.

The only thing I got to work was reading the content into a slice of bytes with a huge size, but of course I want the exact size of the file. I want to hash the file content with md5 afterwards.

// 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)

Solution

  • Try ioutil.ReadAll

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

    In your case do;

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

    You may also want to see this example from multipart package docs, https://play.golang.org/p/084tWn65-d