Giter Site home page Giter Site logo

tejazz / gridfs-file-storage Goto Github PK

View Code? Open in Web Editor NEW
50.0 50.0 38.0 1.3 MB

GridFS file storage enabled application to store and retrieve files and images.

HTML 6.59% CSS 10.98% TypeScript 44.45% JavaScript 37.98%
gridfs mongodb multer nodejs react

gridfs-file-storage's People

Contributors

tejazz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

gridfs-file-storage's Issues

req.body is empty

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

gfs is undefined

I'm trying to connect to the database and declare the gfs variable in one file and share it to another file where I want to fetch the file details

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

Download File in Client

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.