Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 如何使用Golang从Mongo GridFS下载文件?_Mongodb_Go_Gridfs - Fatal编程技术网

Mongodb 如何使用Golang从Mongo GridFS下载文件?

Mongodb 如何使用Golang从Mongo GridFS下载文件?,mongodb,go,gridfs,Mongodb,Go,Gridfs,我试图写一个RESTAPI,它有一个基本的文件上传,下载。我可以做上传部分很好,但我有一个困难的时间从gridfs下载文件。有什么建议吗?更新:我想我知道怎么做了。我很好奇是否有人有其他建议: 下面是我现在的样子: func DownloadRecord(w http.ResponseWriter, filename string) error { if !fileExists(filename) { return errors.New("File doesn't exist

我试图写一个RESTAPI,它有一个基本的文件上传,下载。我可以做上传部分很好,但我有一个困难的时间从gridfs下载文件。有什么建议吗?

更新:我想我知道怎么做了。我很好奇是否有人有其他建议:

下面是我现在的样子:

func DownloadRecord(w http.ResponseWriter, filename string) error {
    if !fileExists(filename) {
      return errors.New("File doesn't exist. Nothing to download")
    }
    session := sqlconnecter.GetMongoDBConnection()
    fileDb := session.DB("mydatabase")
    file, err := fileDb.GridFS("fs").Open(filename)
    defer file.Close()
    if err != nil {
      return err
    }
    fileHeader := make([]byte, 512)
    file.Read(fileHeader)
    fileContentType := http.DetectContentType(fileHeader)
    fileSize := file.Size()

    w.Header().Set("Content-Disposition", "attachment; filename="+filename)
    w.Header().Set("Content-Type", fileContentType)
    w.Header().Set("Content-Length", strconv.FormatInt(fileSize, 10))

    file.Seek(0, 0)
    io.Copy(w, file)
    return err
}