'How to save files(images) in mongoDB Atlas with mongofiles?
I have made a React-Blog application with Golang as backend and I am storing html strings in mongoDB in order to save my blogs. Now I would like to have images in these html strings (blogs). I solved this problem with just linking img tags to imgur, but I decided to use mongoDB Atlas to store all of my images.
So my question is:
Is GridFS the best way to store images and if so, how can I use it with mongoDB Atlas in order to upload the images?
Thank you and have a nice day!
Solution 1:[1]
Yes, GridFS is the best way to store image files in MongoDB. Refer this documentation for more info : https://docs.mongodb.com/manual/core/gridfs/
Solution 2:[2]
Gridfs are a good way to upload images. Gridfs its useful when you're trying to store images or files in general up to 16Mb, what Gridfs does with the file is separate it into chucks, and it create two collections in your database, one collection is fs.files and the other are fs.chunks. You can then Download the stream and serve the file. I've been searching for Examples but i haven't found a good and efficient way to do it.
In my case, the user upload a image through a form, i upload the image to mongodb using Gridfs, then i download the file using Gridfs and serve to http. BTW i'm using the official mongo driver pkg.go.dev/go.mongodb.org/mongo-driver/mongo
Here's what i came out
func UploadFileEndPoint(w http.ResponseWriter, r *http.Request) {
// Here we take the file as multipart
_, handler, _ := r.FormFile("image")
uploadFile(handler, handler.Filename, w)
}
func uploadFile(file *multipart.FileHeader, filename string, w http.ResponseWriter) {
// open the file
filecontent, _ := file.Open()
// Converted to []bytes
dataFile, _ := ioutil.ReadAll(filecontent)
// db.DBConnect connects with your database
db := db.DBConnect
// We set the metadata
uploadopt := options.GridFSUpload().SetMetadata(bson.D{{"metadata tag", "tag"}})
// we create a new bucket and set the database to create the collections fs.files , fs.chunks
bucket, err := gridfs.NewBucket(
db.Database("test"),
)
if err != nil {
// Handle Error
}
// Here we upload the file passing the filename(you can change the name)
// Also we pass the datafile that is a slice of bytes and create a new buffer
// And finally we pass the metadata
FILEID, err := bucket.UploadFromStream(filename, bytes.NewBuffer(dataFile), uploadopt)
if err != nil {
// Handle Error
}
log.Println("New File Created, The file size::", file.Size)
// we print the id of the file
// with this id we're gonna be able to download the file
log.Println("This is the ID::", FILEID)
w.WriteHeader(http.StatusCreated)
// In this function we pass the response writer and the FileID
ServeImage(w, FILEID)
}
func ServeImage(w http.ResponseWriter, filename primitive.ObjectID) {
db := db.DBConnect
// Create new bucket
bucket, err := gridfs.NewBucket(db.Database("test"))
if err != nil {
// Handle Error Here
}
// Here we download the file and serve it to the response writer
_, err = bucket.DownloadToStream(filename, w)
if err != nil {
// Handle error here
}
w.WriteHeader(http.StatusOK)
}
If there's a better way to do this please feel free to comment
I hope i help you!!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Techgeek |
| Solution 2 |
