2013-02-16 97 views
0

我想上傳我的GAE應用程序中的文件。如何使用Go上傳並使用r.FormValue()在Google App Engine中上傳文件?上傳文件在GAE去

+2

會很高興地看到發生了什麼嘗試。 – 2013-02-17 02:58:24

回答

3

我設法通過使用中間返回參數「other」來解決我的問題。下面這些代碼是上傳處理程序內

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保存到數據存儲。

希望這可以幫助其他人。

+0

** **表示只強調,而不是代碼的一部分。 – sagit 2013-02-18 13:55:16

4

你必須去通過Blobstore Go API Overview得到一個想法,並沒有對你怎麼可以存儲&服務使用去谷歌App Engine的用戶數據的full example

我建議你在一個完全獨立的應用程序中做這個例子,因此在試圖將它集成到已經存在的應用程序之前,你可以嘗試一下它。

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)語句之前訪問時引發錯誤)。我希望有人能幫我解決這個問題。謝謝!

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