Last active
January 4, 2023 02:43
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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
Isn’t this just reading the first part of the file, when the file is bigger than Uint8Array?