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

noob

Golang和Sinatra人在这里。我入侵了Sinatra应用程序,以接受从HTML表单发布的上传文件,并通过GridFS将其保存到托管的MongoDB数据库中。这似乎工作正常。我正在使用mgo驱动程序在Golang中编写相同的应用程序。

从功能上来说,它工作正常。但是在Golang代码中,我将文件读入内存,然后使用mgo将文件从内存写入MongoDB。这似乎比我同等的Sinatra应用要慢得多。我感觉到Rack和Sinatra之间的交互不会执行此“中间”或“临时”步骤。

这是我的Go代码的片段:

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", n)

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

}

  • 是否需要此“临时”步骤(data, err := ioutil.ReadAll(file))?
  • 如果是这样,我可以更有效地执行此步骤吗?
  • 我应该考虑其他可接受的做法或方法吗?

谢谢…

回答:

不,您不应该一次在内存中完全读取文件,因为当文件太大时,这会中断。GridFS.Create文档中的第二个示例避免了此问题:

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)

至于为什么它比其他东西慢,在不深入研究所使用的两种方法的细节的情况下很难说出来。

以上是 使用mgo将上传的文件存储在MongoDB GridFS中,而不保存到内存 的全部内容, 来源链接: utcz.com/qa/406398.html

回到顶部