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

问题描述 投票:-2回答:1

我正在尝试编写一个具有基本文件上载,下载的Rest API。我能够上传部分就好了,但我很难从gridfs下载文件。有什么建议 ?

mongodb go gridfs
1个回答
1
投票

更新:我想我想出了怎么做。我很好奇,如果有人有任何其他建议:

以下是它现在的样子:

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
}
© www.soinside.com 2019 - 2024. All rights reserved.