dongzhui2636 2014-03-03 23:20
浏览 388
已采纳

使用mgo将上载的文件存储在MongoDB GridFS中,而不保存到内存

noob Golang and Sinatra person here. I have hacked a Sinatra app to accept an uploaded file posted from an HTML form and save it to a hosted MongoDB database via GridFS. This seems to work fine. I am writing the same app in Golang using the mgo driver.

Functionally it works fine. However in my Golang code, I read the file into memory and then write the file from memory to the MongoDB using mgo. This appears much slower than my equivalent Sinatra app. I get the sense that the interaction between Rack and Sinatra does not execute this "middle" or "interim" step.

Here's a snippet of my Go code:

func uploadfilePageHandler(w http.ResponseWriter, req *http.Request) {
  // Capture multipart form file information
  file, handler, err := req.FormFile("filename")
  if err != nil {
    fmt.Println(err)
  }

  // Read the file into memory
  data, err := ioutil.ReadAll(file)
  // ... check err value for nil

  // Specify the Mongodb database
  my_db := mongo_session.DB("... database name...")

  // Create the file in the Mongodb Gridfs instance
  my_file, err := my_db.GridFS("fs").Create(unique_filename)
  // ... check err value for nil

  // Write the file to the Mongodb Gridfs instance
  n, err := my_file.Write(data)
  // ... check err value for nil

  // Close the file
  err = my_file.Close()
  // ... check err value for nil

  // Write a log type message
  fmt.Printf("%d bytes written to the Mongodb instance
", n)

  // ... other statements redirecting to rest of user flow...
}

Question:

  • Is this "interim" step needed (data, err := ioutil.ReadAll(file))?
  • If so, can I execute this step more efficiently?
  • Are there other accepted practices or approaches I should be considering?

Thanks...

  • 写回答

2条回答 默认 最新

  • dongxuan1660 2014-03-05 14:28
    关注

    No, you should not read the file entirely in memory at once, as that will break when the file is too large. The second example in the documentation for GridFS.Create avoids this problem:

    file, err := db.GridFS("fs").Create("myfile.txt")
    check(err)
    messages, err := os.Open("/var/log/messages")
    check(err)
    defer messages.Close()
    err = io.Copy(file, messages)
    check(err)
    err = file.Close()
    check(err)
    

    As for why it's slower than something else, hard to tell without diving into the details of the two approaches used.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!