In JavaScript, I’ve the below code that is capturing an image as blob
:
// Create XHR
var xhr = new XMLHttpRequest(),
blob;
xhr.open("GET", "https://i.imgur.com/m1UIjW1.jpg", true);
// Set the responseType to blob
xhr.responseType = "blob";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
console.log("Image retrieved");
// File as response
blob = xhr.response;
// Put the received blob into IndexedDB
putElephantInDb(blob);
}
}, false);
// Send XHR
xhr.send();
The most critical line here is: xhr.responseType = "blob";
In GO WebAssembly I was able to download the same file using:
func (db *DataBase) init(dataSet, table string) {
var Ok, Err, Upgrade js.Func
db.Request = Window.Get("indexedDB").Call("open", dataSet, 1)
Upgrade = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
defer Upgrade.Release()
go func(this js.Value, fullUrlFile string) {
db.Data = this.Get("result")
Store := db.Data.Call("createObjectStore", table, map[string]interface{}{"keyPath": "id"})
fullUrlFile = "https://i.imgur.com/m1UIjW1.jpg"
var blob *bytes.Buffer
r, e := http.Get(fullUrlFile)
if e != nil {
panic(e)
}
defer r.Body.Close()
// Get file name
fileUrl, e := url.Parse(fullUrlFile)
if e != nil {
panic(e)
}
path := fileUrl.Path
segments := strings.Split(path, "/")
fileName = segments[len(segments)-1]
println(fileName)
// Create blob
var dest []byte
blob = bytes.NewBuffer(dest)
io.Copy(blob, r.Body)
/*** Save to file ***
f, e := os.Create(fileName) // "m1UIjW1.jpg"
if e != nil {
panic(e)
}
defer f.Close()
n, e := f.ReadFrom(blob)
if e != nil {
panic(e)
}
fmt.Println("File size: ", n)
**********************//
/*** Save to DataBase ***/
Store.Call("add", map[string]interface{}{"id": "00-03", "name": "Karam", "age": 19, "email": "kenny@planet.org", "image": blob})
/**********************/
Window.Call("alert", "First record posted.")
}(this, fullUrlFile)
return nil
})
db.Request.Set("onupgradeneeded", Upgrade)
}
For wasm
I committed the save to file
lines and replaced them with the save to DataBase
but I got an error:
panic: ValueOf: invalid value
At "image": blob
, which means the blob
is not mapped properly to the browser.
Any thought?