tejazz / gridfs-file-storage Goto Github PK
View Code? Open in Web Editor NEWGridFS file storage enabled application to store and retrieve files and images.
GridFS file storage enabled application to store and retrieve files and images.
What is the recommended approach to update a file?
Hi I tried this code below with values for both caption and filename:
`
let formData = new FormData();
formData.append('caption', caption);
formData.append('file', {
name: filename
});
console.log('upload File formData: ', formData);
axios.post('http://localhost:9890/', formData)
.then((response) => {
response.data.success ? alert('File successfully uploaded') : alert('File already exists');
this.fetchRecent();
})
.catch(err => alert('Error: ' + err));
`
When I uploaded an image file, on the server side, the logging showed the req.body is empty and req.file is undefined:
Upload single file req.body: {}
Upload single file req.file: undefined
The server side code:
`
imageRouter.route('/')
.post(upload.single('file'), (req, res, next) => {
console.log(req.body);
// check for existing images
Image.findOne({ caption: req.body.caption })
.then((image) => {
console.log(image);
if (image) {
return res.status(200).json({
success: false,
message: 'Image already exists',
});
}
`
...
Do you have an idea what I did wrong?
Thanks
mongo.connection.js
const mongoose = require("mongoose");
const Grid = require("gridfs-stream");
let gfs;
const establishConnection = async () => {
try {
mongoose.set("strictQuery", false);
await mongoose.connect(process.env.DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const connect = mongoose.connection;
connect.on("error", (err) => {
console.error("Mongoose connection error:", err);
});
connect.once("open", () => {
gfs = new mongoose.mongo.GridFSBucket(connect.db, { bucketName: "uploads" });
console.log("Mongoose connection successful.");
});
} catch (err) {
console.error("Mongoose connection error:", err);
throw err;
}
};
const getGfsInstance = () => {
if (!gfs) {
throw new Error("Connection not established. Call establishConnection first.");
}
return gfs;
};
module.exports = { establishConnection, getGfsInstance };
user.controller.js
const { gfs } = require("../connnection/mongo.connection");
exports.postRetriveAll = async (res, req) => {
try {
// await establishConnection();
console.log("Retrieved gfs:", gfs);
// Retrieve all file details from the "uploads" bucket
gfs.find({}).toArray((err, files) => {
if (err) {
console.error("Error:", err);
} else {
console.log("Files:", files);
}
});
}
catch (err) {
console.log(err);
return err;
}
};
Output
Mongoose connection successful.
Retrieved gfs: undefined
TypeError: Cannot read properties of undefined (reading 'find')
i have called establishConnection() function in app.js file initially and also called it once again in user.controller.js but it didn't worked i also used the promise method but it didn't work
I've been trying to follow your tutorial and so far I'm stuck on how to download the file in the client
imageRouter.route("/file/:filename").get((req, res, next) => {
gfs.find({ filename: req.params.filename }).toArray((err, files) => {
if (!files[0] || files.length === 0) {
return res.status(200).json({
success: false,
message: "No files available",
});
}
console.log("getter", files[0]);
res.status(200).json({
success: true,
file: files[0],
});
});
});
I am using React and already spent two days trying to download the file in the client. I know the the uploading is right since I can see the file and download the file using sa NoSQLBooster MongoDB Client
My use case is when i have the list the user can have the option to download the file..
Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.