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 ?
Asked
Active
Viewed 1,254 times
1 Answers
1
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
}

Plawan Rath
- 42
- 6