0

I'm trying to the images submitted through HTML form and then upload those in the imagekit through node app. I'm completely lost with the configuration. Any help would be greatly appreciated.

const app = express();
const multer = require('multer');
const path = require('path');
const upload = multer({
    dest: "uploads/" // "uploads"
});


var ImageKit = require("imagekit");
var fs = require('fs');


app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.urlencoded({extended: true}));


var imagekit = new ImageKit({
    publicKey : "public_6ImvGNsOViPhZ*******",
    privateKey : "private_IZ1pjwUR9F********",
    urlEndpoint : "https://ik.imagekit.io/*****/"
});




app.get('/upload', (req, res) => {
    res.render('index')
})

app.post('/upload', upload.single("image"), (req, res) => {
    fs.readFile('uploads/' + req.file.filename, function(err, data) {
        if (err) throw err; // Fail if the file can't be read.
        imagekit.upload({
          file : req.file, //required
          fileName : req.file.filename + '.jpg', //required
          tags: ["tag1", "tag2"]
        }, function(error, result) {
          if(error) console.log(error);
          else console.log(result);
        });
      });
    console.log(req.file.filename);
    res.redirect('/upload');
})

2 Answers2

0

You don't need to send your images to the node app and then upload them, you can directly upload your images from the client-side with a backend authentication endpoint. You can use imagekit-javascript sdk for this. It also has a sample app which you can refer to.

  • This approach is problematic as you cannot enforce a specific filename is used. This way, the client-side can overwrite files in the server. – Morton Oct 18 '22 at 13:37
0

First setup a middleware for Multer and inside it set the storage destination to memory:

    module.exports=(req, res, next) =>{
    const uploadFiles = multer({storage:multer.memoryStorage()}).single('image'); //'image' = the input name  in will be in the form
    uploadFiles(req, res, err => {
        if (err instanceof multer.MulterError) { // A Multer error occurred when uploading.
            if (err.code === "LIMIT_UNEXPECTED_FILE") { // Too many images exceeding the allowed limit
            // ...
            }
        } else if (err) {
            // handle other errors
        }
    
        // Everything is ok.
        next();
    });
}

then in your post request do this:

    exports.addImage = async (req, res, next) => {

    await imagekit.upload({
        file : req.file.buffer, //required
        fileName : req.file.originalname, //required
        folder:'myFolder', // optional
      }, function(error, result) {
        if(error) console.log(error);
        else
        return res.status(200).json({
            message:result
        })
    });
}
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Mohamed Aarab
  • 846
  • 1
  • 11
  • 16