How to change filename using Multer on NodeJS?

var i=0;

storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const dir =  './uploads/'
    console.log(file)
      return cb(null,dir)
  },
  filename: (req, file, cb) => {
    i++;
    cb(null, Date.now() + '-' + 'Applicant' + '-' + i);
  }
})

But Multer always saves it as: img-1676302140202.jpeg or whichever timestamp and extension as long as it is jpg/jpeg, png or webp. But always as 'img', the timestamp but not the counter nor the word 'Applicant'. Can somebody tell me what im doing wrong and/or how can I achieve the desired filename "Date.now() + '-' + 'Applicant' + '-' + I"?

******* EDIT **********

As requested in the comments here is the entire setup:

var express = require('express');
var fs = require('fs');
var moment = require('moment');
var router = express.Router();
const multer = require('multer');
const path = require('path');
const base64ToImage = require('base64-to-image');
const homePath = require("os").homedir()
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const { Sequelize, INTEGER} = require("sequelize");
const { extname } = require('path');
const { request } = require('express');
const { Int } = require('mssql');

const sequelize = new Sequelize(config.database, config.username, config.password, {
  host: 'localhost',
  dialect: 'mssql'
});
const Op = Sequelize.Op;

const applicant = require("../models").Applicants;
const personalDocument = require("../models").PersonalDocuments;
const city = require("../models").Cities;
const State = require("../models").States;
const civilState = require("../models").CivilState;
const family = require("../models").Families;
const dependent = require("../models").Dependents;
const workExperience = require("../models").WorkExperience;
const language = require("../models").Languages;
const job = require("../models").Jobs;
const study = require("../models").Studies;
const reference = require("../models").References;

applicant.hasMany(personalDocument),
applicant.belongsTo(city),
applicant.belongsTo(state),
applicant.belongsTo(civilState),
applicant.hasMany(family),
applicant.hasMany(dependent),
applicant.hasMany(workExperience),
applicant.hasMany(language),
applicant.belongsTo(job),
applicant.hasMany(study),
applicant.hasMany(reference)

var upload = null;
var storage = null;

async function createDir(){
  await fs.mkdir("./uploads", function(err) {
    if (err) {
      console.log(err)
    } else {
      console.log("New directory successfully created.")
    }
  })
}

createDir()

var i=0;

storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const dir =  './uploads/'
    console.log(file)
      return cb(null,dir)
  },
  filename: (req, file, cb) => {
    i++;
    cb(null, Date.now() + '-' + 'Applicant' + '-' + i);
  }
})

upload = multer({storage});

//post New Applicant
router.post('/postNewApplicant', upload.single('file'),async function(request, response){
  var imageName = request.body.imageName;
  var base64Str = request.body.applicantImage;
  var pathString  = './uploads/';
  var optionaObj = {
    'filename': imageName,
  };

  var imageInfo = base64ToImage(base64Str, pathString, optionaObj);

  var imagePath = pathString + imageInfo.fileName;

  try{
    let apply = await applicant.create({
        firstName: request.body.firstName,
        secondName: request.body.secondName,
        lastName: request.body.lastName,
        secondLastName: request.body.secondLastName,
        nationality: request.body.nationality,
        applicantImage: imagePath,
        country: request.body.country,
        birthDate: request.body.birthDate,
        CivilStateId: request.body.CivilStateId,
        StateId: request.body.StateId,
        CityId: request.body.CityId,
        JobId: request.body.JobId,
    });
    return response.status(200).json({
      "idApplicant": apply.id
    }) ;
  }
  catch
    (error){
      console.log('Error',error.message);
      return response.status(500).json({
        error,
      })
    }
  }
);

********* EDIT *********

Actually my bad, turns out I had a syntax error in:

  var imageName = request.body.imageName;
  var base64Str = request.body.applicantImage;
  var pathString  = './uploads/';
  var optionaObj = {
    'filename': imageName,
  };

  var imageInfo = base64ToImage(base64Str, pathString, optionaObj);

  var imagePath = pathString + imageInfo.fileName;

In:

var optionaObj = {
            'filename': imageName,
          };

'filename' should be 'fileName', that's why it keeps naming it as a default 'img - timestamp'. It works perfectly now. Hope it helps someone that's having the same silly mistake as me.



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation