【问题标题】:How to read file from disk and pass it to WebAssembly using Go?如何使用 Go 从磁盘读取文件并将其传递给 WebAssembly?
【发布时间】:2019-06-14 08:21:31
【问题描述】:

具体来说,如何在 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
}

【问题讨论】:

  • 出于安全原因,您不能在浏览器中与本地文件系统进行交互。
  • 也许你需要使用syscall/jsblog.gopheracademy.com/advent-2018/go-in-the-browser调用FileReader JavaScript API(developer.mozilla.org/en-US/docs/Web/API/File/…
  • @Adrian 你当然可以,你只需要让用户给你文件。有 API,也有上传输入。
  • @donatJ 这与与本地文件系统交互不同。您不能从 JavaScript 打开任意文件路径或检查目录。访问文件的唯一方法是用户将其提供给文件表单字段。

标签: javascript go webassembly


【解决方案1】:

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

文件读取方法甚至默认返回错误。

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

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

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

【讨论】:

    猜你喜欢
    • 2018-01-14
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    相关资源
    最近更新 更多