Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert binary File to array of bytes

I’m wondering what is the best way to convert binary File to []byte

Here is a sample code that doesn’t work. I’m wondering how I should adjust it to return the content as

func ReadFileAndReturnByteArray(extractedFilePath string) ([]byte, error) {
    file, err := os.Open(extractedFilePath)
    if err != nil {
        return nil, err
    }
    defer file.Close()

    fileinfo, err := file.Stat()
    if err != nil {
        fmt.Println(err)
        return nil, err
    }

    filesize := fileinfo.Size()
    buffer := make([]byte, filesize)

    _, err = file.Read(buffer)
    if err != nil {
        fmt.Println(err)
        return  nil, err
    }
    return buffer, nil
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The os package provides a ReadFile function which only works for files. It has the exact same signature as your ReadFileAndReturnByteArray function and should be a drop-in replacement.


The io package provides the ReadAll function which works for any io.Reader.

Example:

func ReadFileAndReturnByteArray(extractedFilePath string) ([]byte, error) {
    file, err := os.Open(extractedFilePath)
    if err != nil {
        return nil, err
    }
    defer file.Close()

    return io.ReadAll()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading