我正在尝试在我的 GAE 应用程序中上传文件。如何使用 Go 在 Google App Engine 中上传文件并使用r.FormValue()
?
4 回答
您必须通过Blobstore Go API 概述来获得一个想法,并且有一个完整的示例说明如何使用 Go 在 Google App Engine 上存储和提供用户数据。
我建议你在一个完全独立的应用程序中做这个例子,这样你就可以在尝试将它集成到你现有的应用程序之前尝试一段时间。
我设法通过使用中间返回参数“其他”来解决我的问题。下面的这些代码在上传处理程序中
blobs, other, err := blobstore.ParseUpload(r)
然后分配对应的formkey
file := blobs["file"]
**name := other["name"]** //name is a form field
**description := other["description"]** //descriptionis a form field
并在我的结构值赋值中像这样使用它
newData := data{
Name: **string(name[0])**,
Description: **string(description[0])**,
Image: string(file[0].BlobKey),
}
datastore.Put(c, datastore.NewIncompleteKey(c, "data", nil), &newData )
不是 100% 确定这是正确的,但这解决了我的问题,它现在正在将图像上传到 blobstore 并将其他数据和 blobkey 保存到数据存储区。
希望这也可以帮助其他人。
我已经尝试了这里https://developers.google.com/appengine/docs/go/blobstore/overview的完整示例,并且在 blobstore 中上传并提供服务时效果很好。
但是插入要保存在数据存储中某处的额外帖子值会擦除“r.FormValue()”的值吗?请参考下面的代码
func handleUpload(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
//tried to put the saving in the datastore here, it saves as expected with correct values but would raised a server error.
blobs, _, err := blobstore.ParseUpload(r)
if err != nil {
serveError(c, w, err)
return
}
file := blobs["file"]
if len(file) == 0 {
c.Errorf("no file uploaded")
http.Redirect(w, r, "/", http.StatusFound)
return
}
// a new row is inserted but no values in column name and description
newData:= data{
Name: r.FormValue("name"), //this is always blank
Description: r.FormValue("description"), //this is always blank
}
datastore.Put(c, datastore.NewIncompleteKey(c, "Data", nil), &newData)
//the image is displayed as expected
http.Redirect(w, r, "/serve/?blobKey="+string(file[0].BlobKey), http.StatusFound)
}
不能将上传与常规数据结合起来吗?为什么 r.FormValue() 的值除了文件(输入文件类型)之外似乎消失了?即使我必须在将 blobkey 关联到其他数据之前先强制上传,作为上传的结果,这也是不可能的,因为我无法将任何 r.FormValue() 传递给上传处理程序(就像我说的那样变为空,或者在 blob、_、err := blobstore.ParseUpload(r) 语句之前访问时会引发错误)。我希望有人能帮我解决这个问题。谢谢!
除了使用 Blobstore API 之外,您可以只使用该Request.FormFile()
方法来获取文件上传内容。使用net\http包文档获取更多帮助。
blobstore.UploadUrl()
直接使用请求允许您在处理上传 POST 消息之前跳过设置。
一个简单的例子是:
func uploadHandler(w http.ResponseWriter, r *http.Request) {
// Create an App Engine context.
c := appengine.NewContext(r)
// use FormFile()
f, _, err := r.FormFile("file")
if err != nil {
c.Errorf("FormFile error: %v", err)
return
}
defer f.Close()
// do something with the file here
c.Infof("Hey!!! got a file: %v", f)
}