douliexu5623 2018-03-05 20:27
浏览 338

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

I am trying to write a Rest API which has a basic file upload, download. I am able to do the upload part just fine but I am having a hard time downloading file from gridfs. ANy suggestions ?

  • 写回答

1条回答 默认 最新

  • dongtuo5611 2018-03-05 21:52
    关注

    UPDATE: I think I figured out how to do it. I am curious if any one has any other suggestions:

    Here is how it looks for me right now:

    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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号