Skip to content

Instantly share code, notes, and snippets.

@nicolas-oliveira
Last active June 30, 2020 17:46
Show Gist options
  • Save nicolas-oliveira/34656e0dd4b355c46b284c770ce33b01 to your computer and use it in GitHub Desktop.
Save nicolas-oliveira/34656e0dd4b355c46b284c770ce33b01 to your computer and use it in GitHub Desktop.
Transform Original name file to hash hex name with multer and crypto configuration

Multer conversion file to hex hash exemple:

multerConfig.js

const multer = require('multer');
const crypto = require('crypto');
const path = require('path');

module.exports = {
  storage: multer.diskStorage({
    destination: path.resolve(__dirname, '..', '..', 'tmp', 'uploads'),
    filename: (request, file, callback) => {
      crypto.randomBytes(16, (err, response) => {
        if (err) return callback(err);
        return callback(
          null,
          response.toString('hex') + path.extname(file.originalname)
        );
      });
    },
  }),
};

routes.js

[...]

const multer = require('multer');
const multerConfig = require('./config/multerConfig');

[...]

const upload = multer(multerConfig); // abstrated configuration

[...]

routes.post('/file', upload.single('file'), FileController.store);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment