How to store a file with file extension with multer?

后端 未结 11 1640
情话喂你
情话喂你 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: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 });
    

提交回复
热议问题