在GAE Go中上传文件

huangapple go评论83阅读模式
英文:

Upload file in GAE Go

问题

我正在尝试在我的GAE应用程序中上传文件。如何在Google App Engine中使用Go语言和r.FormValue()来上传文件?

英文:

I am trying to upload a file in my GAE app. How do I the upload of a file in Google App Engine using Go and using the r.FormValue()?

答案1

得分: 4

你需要阅读Blobstore Go API概述来了解情况,并且有一个完整的示例展示了如何使用Go在Google App Engine上存储和提供用户数据。

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

英文:

You have to go through the Blobstore Go API Overview to get an idea and there is a full example on how could you store & serve user data on Google App Engine using Go.

I would suggest you to do that example in a completely separate application, so you'll be able to experiment with it for a while before trying to integrate it to your already existing one.

答案2

得分: 3

我通过使用中间返回参数"other"成功解决了我的问题。以下代码位于上传处理程序中:

blobs, other, err := blobstore.ParseUpload(r)

然后分配相应的表单键:

file := blobs["file"]
**name := other["name"]** //name是一个表单字段
**description := other["description"]** //description是一个表单字段

并在我的结构值分配中使用它:

newData := data{
  Name: **string(name[0])**,
  Description: **string(description[0])**,
  Image: string(file[0].BlobKey),          
}

datastore.Put(c, datastore.NewIncompleteKey(c, "data", nil), &newData )

不能百分之百确定这是正确的,但这解决了我的问题,现在可以将图像上传到blobstore并将其他数据和blobkey保存到datastore中。

希望这对其他人也有所帮助。

英文:

I managed to solve my problem by using the middle return param, "other". These code below are inside the upload handler

blobs, other, err := blobstore.ParseUpload(r)

Then assign corresponding formkey

file := blobs["file"]
**name := other["name"]** //name is a form field
**description := other["description"]** //descriptionis a form field

And use it like this in my 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 )

Not 100% sure this is the right thing but this solves my problem and it is now uploading the image to blobstore and saving other data and blobkey to datastore.

Hope this could help others too.

答案3

得分: 0

我已经尝试了这里的完整示例https://developers.google.com/appengine/docs/go/blobstore/overview,并且在blobstore中进行上传并提供服务时运行良好。

但是,将额外的post值插入到数据存储中以保存在某个地方会擦除“r.FormValue()”的值?请参考下面的代码

func handleUpload(w http.ResponseWriter, r *http.Request) {
        c := appengine.NewContext(r)

        //尝试将保存放在这里的数据存储中,它按预期保存了正确的值,但会引发服务器错误。

        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
        }
        
        //插入了一行新数据,但列名和描述中没有值
        newData:= data{
          Name: r.FormValue("name"), //这总是空白的
          Description: r.FormValue("description"), //这总是空白的
        }
        
        datastore.Put(c, datastore.NewIncompleteKey(c, "Data", nil), &newData)

        //图像按预期显示
        http.Redirect(w, r, "/serve/?blobKey="+string(file[0].BlobKey), http.StatusFound)
}

无法将上传与常规数据结合吗?为什么r.FormValue()的值似乎会消失,除了文件(输入文件类型)之外?即使我必须在关联blobkey之前强制先上传,作为上传的结果,到其他数据,也不可能,因为我无法将任何r.FormValue()传递给上传处理程序(如我所说,它变为空,或者在blobs,_,err := blobstore.ParseUpload(r)语句之前访问时会引发错误)。我希望有人能帮助我解决这个问题。谢谢!

英文:

I have tried the full example from here https://developers.google.com/appengine/docs/go/blobstore/overview, and it worked fine doing the upload in blobstore and serving it.

But inserting extra post values to be saved somewhere in the datastore erases the values of "r.FormValue() "? Please refer to the code below

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)
}

Is it not possible to combine the upload with regular data? How come the values of r.FormValue() seems to disappear except for the file (input file type)? Even if I would have to force upload first before associating the blobkey, as the result of the upload, to other data, it would not be possible since I could not pass any r.FormValue() to the upload handler(which like I said becomes empty, or would raised an error when accessed prior the blobs, _, err := blobstore.ParseUpload(r) statement). I hope someone could help me solve this problem. Thank you!

答案4

得分: 0

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

直接使用Request允许您在处理上传POST消息之前跳过设置blobstore.UploadUrl()

一个简单的示例:

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    // 创建一个App Engine上下文。
    c := appengine.NewContext(r)

    // 使用FormFile()
    f, _, err := r.FormFile("file")
    if err != nil {
            c.Errorf("FormFile error: %v", err)
            return
    }
    defer f.Close()

    // 在这里处理文件
    c.Infof("Hey!!! got a file: %v", f)
}
英文:

In addition to using the Blobstore API, you can just use the Request.FormFile() method to get the file upload content. Use net\http package documentation for additional help.

Using the Request directly allows you to skip setting up an blobstore.UploadUrl() before handling the upload POST message.

A simple example would be:

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)
}

huangapple
  • 本文由 发表于 2013年2月16日 23:58:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/14912188.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定