在GAE Go中上传文件

时间:2013-02-16 15:58:52

标签: file google-app-engine upload go

我正在尝试在我的GAE应用中上传文件。如何使用Go并使用r.FormValue()

在Google App Engine中上传文件

4 个答案:

答案 0 :(得分:4)

你必须通过Blobstore Go API Overview才能得到一个想法,并且有一个full example关于你如何存储&使用Go。在Google App Engine上提供用户数据。

我建议您在一个完全独立的应用程序中执行该示例,这样您就可以在尝试将其集成到现有应用程序之前尝试一段时间。

答案 1 :(得分:3)

我设法通过使用中间返回参数“其他”来解决我的问题。下面的代码在上传处理程序

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

在我的struct value assignment

中使用它
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保存到数据存储区。

希望这也可以帮助其他人。

答案 2 :(得分:0)

我已经尝试了这里的完整示例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)语句)。我希望有人能帮我解决这个问题。谢谢!

答案 3 :(得分:0)

除了使用Blobstore API之外,您还可以使用Request.FormFile()方法获取文件上载内容。使用net\http包文档获取其他帮助。

直接使用请求可以在处理上传POST消息之前跳过设置blobstore.UploadUrl()

一个简单的例子是:

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)
}
相关问题