Store Uploaded File in MongoDB GridFS Using mgo without Saving to Memory

China☆狼群 提交于 2019-12-04 12:11:05

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.

Once you have the file from multipartForm, it can be saved into GridFs using below function. I tested this against huge files as well ( upto 570MB).

//....code inside the handlerfunc
for _, fileHeaders := range r.MultipartForm.File {
        for _, fileHeader := range fileHeaders {
            file, _ := fileHeader.Open()            
            if gridFile, err := db.GridFS("fs").Create(fileHeader.Filename); err != nil {
                //errorResponse(w, err, http.StatusInternalServerError)
                return
            } else {
                gridFile.SetMeta(fileMetadata)
                gridFile.SetName(fileHeader.Filename)
                if err := writeToGridFile(file, gridFile); err != nil {
                    //errorResponse(w, err, http.StatusInternalServerError)
                    return
                }
func writeToGridFile(file multipart.File, gridFile *mgo.GridFile) error {
    reader := bufio.NewReader(file)
    defer func() { file.Close() }()
    // make a buffer to keep chunks that are read
    buf := make([]byte, 1024)
    for {
        // read a chunk
        n, err := reader.Read(buf)
        if err != nil && err != io.EOF {
            return errors.New("Could not read the input file")
        }
        if n == 0 {
            break
        }
        // write a chunk
        if _, err := gridFile.Write(buf[:n]); err != nil {
            return errors.New("Could not write to GridFs for "+ gridFile.Name())
        }
    }
    gridFile.Close()
    return nil
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!