skip to Main Content

I am new to Next js, what are the possible ways to upload files in mongodb using nextjs. Is it possible to upload directly in mongodb,if not what are the best hosting websites to upload my files. Thanks in advance

I have tried some code works well in react and I want solution for Nextjs framework

2

Answers


  1. You can not directly upload images in mongodb, you need an URL of uploaded image, so you need an image host platform.

    You can use https://cloudinary.com/

    or either you can store base64 of image, but i guess this is not a good and optimal solution

    Login or Signup to reply.
  2. You can store the URL of the image or base64 of the image in the MongoDB.

    If you don’t want to store image in base64 format then you can keep the image URL in MongoDB database and upload the image on AWS/Cloudinary or any other platform as per your preference.

    Here is also the sample code for the implementation of this on Cludinary. In your .env file you need to place the given environment variables with their respective values.

    1. CLOUDINARY_CLOUD_NAME
    2. CLOUDINARY_API_KEY
    3. CLOUDINARY_API_SECRET
    import cloudinary from 'cloudinary';
    
    cloudinary.config( {
      cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
      api_key: process.env.CLOUDINARY_API_KEY,
      api_secret: process.env.CLOUDINARY_API_SECRET,
    } );
    
    export default async function handler(req, res) {
      if (req.method === 'POST') {
        const { file } = req.body; // Here is the File in base64 or URL.
    
        cloudinary.uploader.upload(file, function(error, result) {
          if ( error ) {
            res.status(500).json(
            { error }
            );
          } else {
            res.status(200).json(
            { url: result.secure_url }
            );
          }
        });
      } else {
        res.status(405).end();
      }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search