亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Go 從磁盤讀取文件并將其傳遞給 WebAssembly?

如何使用 Go 從磁盤讀取文件并將其傳遞給 WebAssembly?

Go
MYYA 2023-06-01 17:18:18
具體<input type="file">在Go中如何與這個函數對接?我知道有“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}
查看完整描述

2 回答

?
慕容708150

TA貢獻1831條經驗 獲得超4個贊

多年來我一直想要一個滿意的答案,前幾天晚上終于想通了。


您基本上可以將整個事情歸結為:


? ? 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

? ? }))

查看完整回答
反對 回復 2023-06-01
?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

您無法真正在瀏覽器中訪問文件系統。wasm_exec.js用于在瀏覽器中執行 Go webassembly,它模擬了一些文件系統功能,但我認為它對你不是很有用,

文件讀取方法甚至默認返回錯誤。

你提到了<input type="file">。您可以從上傳的文件中獲取字節:Getting byte array through input type = file。然后,您可以將這些字節傳遞給 Golang wasm 運行時。

在您的 Go 代碼中定義一個全局系統調用/js 回調,并從瀏覽器調用它以將字節向下傳遞到 Go 運行時。

我會尋找關于如何在 Go 運行時中定義回調的博文。還要注意 go 1.11 和 1.12 之間的變化,api 有重大變化。


查看完整回答
反對 回復 2023-06-01
  • 2 回答
  • 0 關注
  • 345 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號