Skip to content

Instantly share code, notes, and snippets.

@donatj
Last active January 4, 2023 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save donatj/0749e1ba40d90aafbae86a413a7e8f42 to your computer and use it in GitHub Desktop.
Save donatj/0749e1ba40d90aafbae86a413a7e8f42 to your computer and use it in GitHub Desktop.
Read File Inputs from Go WASM (used in https://donatstudios.com/Read-User-Files-With-Go-WASM)
package main
import (
"syscall/js"
)
func main() {
quit := make(chan struct{}, 0)
document := js.Global().Get("document")
document.Get("body").Call("insertAdjacentHTML", "beforeend", `
<input type="file" id="fileInput">
<output id="fileOutput"></output>
`)
fileInput := document.Call("getElementById", "fileInput")
fileOutput := document.Call("getElementById", "fileOutput")
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)
out := string(dst)
if len(out) > 100 {
out = out[:100] + "..."
}
fileOutput.Set("innerText", out)
return nil
}))
return nil
}))
<-quit
}
@elgohr
Copy link

elgohr commented Aug 20, 2022

Isn’t this just reading the first part of the file, when the file is bigger than Uint8Array?

@donatj
Copy link
Author

donatj commented Aug 20, 2022

@elgohr

if len(out) > 100 {
	out = out[:100] + "..."
}

This part is limiting it to the first hundred bytes for demonstrative purposes, but the Uint8Array can hold an arbitrary amount of data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment