Breaking

Upload File To Cloudinary Using Node.JS Multer - Upload Image or File

 



package.json


{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cloudinary": "^1.23.0",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "ejs": "^3.1.5",
    "express": "^4.17.1",
    "multer": "^1.4.2",
    "nodemon": "^2.0.6"
  }
}


index.js


require('dotenv').config();

const express = require('express');
const upload = require("./utils/multer");
const {cloudinary} = require("./utils/cloudinary");
const { all } = require('async');

const app = express();






app.set('view engine', 'ejs');
app.use(express.json({limit: "50m"}));
app.use(express.urlencoded({limit: "50mb", extended: false}));

app.get('/api/upload', async (req, res, next)=>{
    // SINGLE IMAGE 
    // const single_image = await cloudinary.api.resources();
    // console.log(single_image.resources[0].public_id);


    // const single_image = await cloudinary.api.resource("yqxprxoayhnhjtdmnpsi");
    // console.log(single_image);
    // https://cloudinary.com/documentation/admin_api#get_resources
    const all_image = await cloudinary.api.resources();
    console.log(all_image);
    const images = await all_image.resources;
    console.log(images);

res.render('index', {images});
});

app.post('/api/upload', upload.single('img') , async (req, res, next)=>{


    console.log("file details: ", req.file);

    // cloudinary.v2.uploader.upload(file, options, callback);
    const result = await cloudinary.uploader.upload(req.file.path);


    console.log("result: ", result);


    const post_details = {
        title: req.body.title,
        image: result.public_id
    }

    res.status(200).json({post_details});
});

const port = process.env.PORT || 5000;
app.listen(port, ()=> console.log('Server is running on : ' + port));


utils/cloudinary.js


const cloudinary = require('cloudinary').v2;



cloudinary.config({
    cloud_name: process.env.CLOUD_NAME,
    api_key: process.env.API_KEY,
    api_secret: process.env.API_SECRET
});



module.exports = {cloudinary};


utils/multer.js


const multer = require('multer');


module.exports = multer({
    storage: multer.diskStorage({}),
    fileFilter: (req, file, cb) => {

        // The function should call `cb` with a boolean
        // to indicate if the file should be accepted

        if (!file.mimetype.match(/png||jpeg||jpg||gif$i/)) {
            // You can always pass an error if something goes wrong:
            cb(new Error('File does not support'), false);
            return;
        }

        // To accept the file pass `true`, like so:
        cb(null, true);
    }
});


views/index.ejs


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <h2>FIle upload</h2>
    <form action="/api/upload" method="POST" enctype="multipart/form-data">
        <div class="field">
            <label for="title">Title</label>
            <input type="text" name="title" id="">
        </div>
        <div class="field">
            <label for="file">File</label>
            <input type="file" name="img" id="">
        </div>
        <div class="field">
            <input type="submit" >
        </div>
    </form>

    <div class="container">
    <% images.forEach(img=>{ %>
        <img src=<%= img.url %> height="200" alt="">
    <% }) %>
    </div>
</body>
</html>


No comments:

Powered by Blogger.