How to read file from disk and pass it to WebAssembly using Go?

Issue

Specifically, how to connect <input type="file"> with this function in Go?
I know there is “syscall/js” package, but I didn’t find any examples with file reading.

func parseCSVFile(filePath string) []LabelWithFeatures {
    fileContent, _ := ioutil.ReadFile(filePath)
    lines := bytes.Split(fileContent, newline)
    numRows := len(lines)

    labelsWithFeatures := make([]LabelWithFeatures, numRows-2)

    for i, line := range lines {
        // skip headers
        if i == 0 || i == numRows-1 {
            continue
        }
        labelsWithFeatures[i-1] = NewLabelWithFeatures(bytes.Split(line, comma))
    }
    return labelsWithFeatures
}

Solution

I’ve wanted a satisfactory answer for this for years, finally figured it out the other night.

You can essentially boil the whole thing down to:

    fileInput := document.Call("getElementById", "fileInput")

    fileInput.Set("oninput", js.FuncOf(func(v js.Value, x []js.Value) any {
        fileInput.Get("files").Call("item", 0).Call("arrayBuffer").Call("then", js.FuncOf(func(v js.Value, x []js.Value) any {
            data := js.Global().Get("Uint8Array").New(x[0])
            dst := make([]byte, data.Get("length").Int())
            js.CopyBytesToGo(dst, data)
            // the data from the file is in dst - do what you want with it
            

            return nil
        }))

        return nil
    }))

I wrote a little blog post about it here with the working WASM code running at the bottom

https://donatstudios.com/Read-User-Files-With-Go-WASM

Answered By – donatJ

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.