[英]Parse javascript Blob in golang
在 Go 中,您可以使用r.ParseMultipartForm()
讀取使用 Ajax 和FormData發送的Form
,該Form
使用表單請求數據填充Form
映射。
func form(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(500) //
fmt.Fprintf(w, "This is the value of %+v", r.Form)
}
但是,我還沒有找到解析 Blob 的方法。 每當我發送一個 Blob 而不是發送表單時,上面的代碼就會返回一個空映射。 也就是說,當我發送這個:
var blob = new Blob([JSON.stringify(someJavascriptObj)]);
//XHR initialization, etc. etc.
xhr.send(blob);
上面的 Go 代碼不起作用。 現在,當我發送這個:
var form = new FormData(document.querySelector("form"));
//...
xhr.send(form);
我可以毫無問題地讀取表單數據。
r.ParseMultipartForm(500)
也許這里返回錯誤? 嘗試捕獲錯誤:
if err := r.ParseMultipartForm(500); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
此外,請考慮提高 500 字節內存限制,因為較大的 blob 將寫入臨時文件。
我認為 javascript 將 blob 視為文件,因此您可以在r.MultipartForm.File
查看它,獲取文件頭,打開它,讀取、解碼和解析。 嘗試例如
r.ParseMultipartForm(500)
fmt.Fprintf(w, "This is the value of %+v", *r.MultipartForm.File)
}
我認為 Javascript 的 Blob 是一個十六進制字符串,最終可以轉換為[]byte
,這是 Go 中 JSON 的標准類型。
// Once you get the blob
blobString := `7b22666f6f223a205b22626172222c202262617a222c2039395d7d`
b, _ := hex.DecodeString(blobString)
json := string(b)
fmt.Println(json) // prints out {"foo": ["bar", "baz", 99]}
您可能想要查看encoding/hex
和encoding/binary
包,以解碼從 Javascript 獲取的 blob,以便在 Go 中鍵入[]byte
,如果還沒有的話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.