如何使用 Go 从磁盘读取文件并将其传递给 WebAssembly?

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

具体来说,如何在Go中连接<input type="file">这个函数? 我知道有 "syscall/js" 包,但我没有找到任何文件读取的例子。

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
}

您无法真正在浏览器中访问文件系统。 wasm_exec.js 用于在浏览器中执行 Go webassembly,它模拟了一些文件系统功能,但我认为它对你不是很有用:https://github.com/golang/go/blob/9d23975d/misc/wasm/wasm_exec.js#L41-L73

文件读取方法甚至returns默认出错。

您提到了 <input type="file">。您可以从上传的文件中获取字节:。然后,您可以将这些字节传递给 Golang wasm 运行时。

在您的 Go 代码中定义一个全局 syscall/js 回调并从浏览器调用它以将字节向下传递到 Go 运行时。

我会寻找有关如何在 Go 运行时中定义回调的博文。还要注意 go 1.11 和 1.12 之间的变化,api 有重大变化。

多年来我一直想要一个满意的答案,前几天晚上终于想通了。

您基本上可以将整个事情归结为:

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

我在这里写了一篇关于它的小博客 post,底部是有效的 WASM 代码 运行

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