I'm trying to upload files to MongoDB with react, and I'm struggling to get the absolute path in order to use GridFS to store the file.
In the backend, I have a route for AddFile defined as such:
const addFile = async (req, res) => {
const { path } = req.body //get absolute path for file
filename = path.split('\\').pop() //extract filename from absolute path
const uploadStream = fs.createReadStream(path).
pipe(bucket.openUploadStream(filename)) //store the file as the filename}
res.json({id : uploadStream.id})
}
in routes, I have the route defined as such:
router.post('/fs', addFile)
this function takes a Json like this
{
"path" : "C:\\Users\\name\\work\\files\\file.json"
}
and returns the MongoDB ObjectId of the file as it is inserted into the database:
{
"id": "6474b6b838e87a34febe8d0b"
}
In the frontend, I have an upload button through which I can add multiple files, and they basically enable me to get the name of the file in the local directory where it was selected from, but not the absolute path I need in order to store the file into GridFS. Is there a better way to upload insert files into mongoDB or is there a way to get the absolute path of a file through upload? Any help would be appreciated!