How to store a file with file extension with multer?

后端 未结 11 1598
情话喂你
情话喂你 2020-12-13 17:56

Managed to store my files in a folder but they store without the file extension.

Does any one know how would I store the file with file extension?

相关标签:
11条回答
  • 2020-12-13 18:11

    I have a workaround for the adding proper extension of files. If you use path node module

    var multer = require('multer');
    var path = require('path')
    
    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, 'uploads/')
      },
      filename: function (req, file, cb) {
        cb(null, Date.now() + path.extname(file.originalname)) //Appending extension
      }
    })
    
    var upload = multer({ storage: storage });
    
    0 讨论(0)
  • 2020-12-13 18:12
    import multer from 'multer';
    import * as shortid from 'shortid';
    import * as mime from 'mime-types';
    
    const storage = multer.diskStorage({
      destination: function (req,file,cb) {
        cb(null, '/path/to/uploads/');
      },
      filename: function (req,file,cb) {
        /* generates a "unique" name - not collision proof but unique enough for small sized applications */
        let id = shortid.generate();
        /* need to use the file's mimetype because the file name may not have an extension at all */
        let ext = mime.extension(file.mimetype);
        cb(null, `${id}.${ext}`);
      }
    });
    
    0 讨论(0)
  • 2020-12-13 18:14

    From the docs: "Multer will not append any file extension for you, your function should return a filename complete with an file extension."

    Here's how you can add the extension:

    var multer = require('multer');
    
    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, 'uploads/')
      },
      filename: function (req, file, cb) {
        cb(null, Date.now() + '.jpg') //Appending .jpg
      }
    })
    
    var upload = multer({ storage: storage });
    

    I would recommend using the mimetype property to determine the extension. For example:

    filename: function (req, file, cb) {
      console.log(file.mimetype); //Will return something like: image/jpeg
    

    More info: https://github.com/expressjs/multer

    0 讨论(0)
  • 2020-12-13 18:15

    I got file the extension from file.mimetype . I split the mimetype and get the file extension from it Please try the below function.

    let storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, './uploads')
      },
      filename: function (req, file, cb) {
        let extArray = file.mimetype.split("/");
        let extension = extArray[extArray.length - 1];
        cb(null, file.fieldname + '-' + Date.now()+ '.' +extension)
      }
    })
    const upload = multer({ storage: storage })
    
    0 讨论(0)
  • 2020-12-13 18:21

    I am doing like this

    var multer  = require('multer');
    
    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, './public/uploads/img/')
      },
      filename: function (req, file, cb) {
        let ext = file.originalname.substring(file.originalname.lastIndexOf('.'), file.originalname.length);
        cb(null, Date.now() + ext);
      }
    })
    
    var upload = multer({ storage: storage }).single('eventimage');
    
    0 讨论(0)
  • 2020-12-13 18:21

    I like to use the original filename for SEO purposes. This requires a bit more checking if the file with the same name already exists. Moreover, extension resolving is done in a few steps to provide maximum flexibility.

    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, 'uploads/')
      },
      filename: function (req, file, cb) {
        // try to get extension from original file name
        var lioDot = file.originalname.lastIndexOf('.');
        if (lioDot !== -1) {
          // I like to use original upload filename for SEO but first lets clean it 
          var newName = file.originalname.substring(0, lioDot).replace(/([^a-z0-9]+)/gi, '-');
          var ext = file.originalname.substring(lioDot, file.originalname.length);
        } else {
          var newName = file.originalname.replace(/([^a-z0-9]+)/gi, '-');
          // try to get extension from mime type string
          var extArray = file.mimetype.split("/");
          var ext = extArray[extArray.length - 1];
          // mime type extension resolving by pure string extraction is not accurate for a lot of types
          // https://www.freeformatter.com/mime-types-list.html
          // it's usually fine for ext strings up to 4 characters, png, jpeg, gif, bmp, tiff ..
          if (ext > 4) {
            // other mime types you would like to support
            var mimetypes = { 'vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx' };
            if (mimetypes.hasOwnProperty(ext)) ext = mimetypes[ext];
          }
        }
    
        var newFullName = newName + ext;
        var i = 0;
        // we need to check if the file with the same name already exists
        // if it exists then we're adding something to make it unique 
        while (fs.existsSync(process.env.PWD + '/uploads/' + newFullName)) {
          newFullName = newName + '-' + ++i + ext;
        }
        cb(null, newFullName);
      }
    })
    
    const upload = multer({ storage: storage });
    
    0 讨论(0)
提交回复
热议问题