更新:我想我知道该怎么做了。我很好奇是否有人有任何其他建议:
这就是我现在的样子:
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
}