I'm following this guide on how to handle file upload in Go: https://cloud.google.com/appengine/docs/go/blobstore/
Scroll down to 'Complete Sample Application' to see the whole code.
I'm trying to handle a POST request with both an image file and some text, but I can't seem to get it working. I want to save the image in Blobstore and I want to save the text in my own struct as its own type called "Item".
Here's my code:
func handleUpload(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
blobs, _, err := blobstore.ParseUpload(r)
if err != nil {
serveError(ctx, w, err)
return
}
file := blobs["file"]
if len(file) == 0 {
log.Errorf(ctx, "no file uploaded")
http.Redirect(w, r, "/", http.StatusFound)
return
}
var n string = r.FormValue("name")
lat, errLat := strconv.ParseFloat(r.FormValue("latitude"), 64)
long, errLong := strconv.ParseFloat(r.FormValue("longitude"), 64)
if errLat != nil {
http.Error(w, "Invalid latitude format: " + errLat.Error(), http.StatusInternalServerError)
}
if errLong != nil {
http.Error(w, "Invalid longitude format: " + errLong.Error(), http.StatusInternalServerError)
}
c := appengine.NewContext(r)
g := Item { Name: n, Date: time.Now(), Latitude: lat, Longitude: long, ImageKey: string(file[0].BlobKey)}
// We set the same parent key on every Greeting entity to ensure each Greeting
// is in the same entity group. Queries across the single entity group
// will be consistent. However, the write rate to a single entity group
// should be limited to ~1/second.
key := datastore.NewIncompleteKey(c, "Item", itemKey(c))
_, err = datastore.Put(c, key, &g)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/serve/?blobKey="+string(file[0].BlobKey), http.StatusFound)
}
When I get down to retrieve the text from the post in
var n string = r.FormValue("name")
The text is empty because it has already been used in the request to save the image. I know that a request can only be "used" once.
My question is: Am I approaching this the wrong way? How would you grab both text and image out of a POST request in Go?
Here's the HTML form:
<html>
<body>
<form action="{{.}}" method="POST" enctype="multipart/form-data">
Name: <br>
<div><textarea name="name" rows="1" cols="60"></textarea></div>
Latitude: <br>
<div><textarea name="latitude" rows="1" cols="60"></textarea></div>
longitude: <br>
<div><textarea name="longitude" rows="1" cols="60"></textarea></div>
Upload File: <input type="file" name="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>