如何使用 multer 存储带有文件扩展名的文件?

How to store a file with file extension with multer?

设法将我的文件存储在一个文件夹中,但它们存储时没有文件扩展名。

有谁知道如何存储带有文件扩展名的文件?

来自文档:"Multer will not append any file extension for you, your function should return a filename complete with an file 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 });

我建议使用 mimetype 属性 来确定扩展名。例如:

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

更多信息:https://github.com/expressjs/multer

我有一个解决方法来添加适当的文件扩展名。如果你使用 path 节点模块

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 });

我从 file.mimetype 获得了文件扩展名。 我拆分 mimetype 并从中获取文件扩展名 请尝试以下功能。

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 })

可以这样做:

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, config.DIR)
    },
    filename: function (req, file, cb) {
        let ext = file.originalname.substring(file.originalname.lastIndexOf('.'), file.originalname.length);
        cb(null, Date.now() + ext)
    }
});
const upload = multer({
    storage: storage
}).any();

我是这样做的

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');

已经回答的代码中可能存在一些问题。

  • 可能有一些 文件没有扩展名
  • 不应有 upload.any() 用法。它 容易受到攻击者的攻击
  • 上传功能应该不是全局的 .

为了更好的安全性,我写了下面的代码。

var storage = multer.diskStorage({
    destination: function (req, file, cb) {

        cb(null, 'temp/')
    },
    filename: function (req, file, cb) {
        let ext = ''; // set default extension (if any)
        if (file.originalname.split(".").length>1) // checking if there is an extension or not.
            ext = file.originalname.substring(file.originalname.lastIndexOf('.'), file.originalname.length);
        cb(null, Date.now() + ext)
    }
})
var upload = multer({ storage: storage });

用于上传

// using only single file object name (HTML name attribute)
// May use upload.array(["file1","file2"]) for more than one
app.post('/file_upload', upload.single("file"), function (req,res) {
    //console.log(req.body, 'Body');
    console.log(req.file, 'file');
    res.send("cool");
})

我使用这个小技巧来获取文件扩展名,并作为一种解决方法来规避当有人两次上传具有相似文件名的文件或服务器中存在的文件时可能发生的问题。

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

let upload = multer({
storage: multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, path.join(__dirname, '../uploads'))
    },
    filename: (req, file, cb) => {
        // randomBytes function will generate a random name
        let customFileName = crypto.randomBytes(18).toString('hex')
        // get file extension from original file name
        let fileExtension = path.extname(file.originalname).split('.')[1];
        cb(null, customFileName + '.' + fileExtension)
    }
  })
})

一种面向对象的方式来存储具有唯一名称的图像

// image.service.ts
import { diskStorage, StorageEngine } from "multer";

class ImageStorageService {

    storage: StorageEngine
    constructor() {
        const MIME_TYPE_MAP = {
            'image/png': 'png',
            'image/jpeg': 'jpg',
            'image/jpg': 'jpg'
        }

        this.storage = diskStorage({
            destination: (req, file, callback) => {
                const isValid = MIME_TYPE_MAP[file.mimetype]
                let error = new Error(`Invalid mime type`)
                if (isValid)
                    error = null

                //app.use(express.static(path.join(`${__dirname}/assets`)))
                callback(error, 'assets/images')
            },
            filename: (req, file, callback) => {
                let currentFileName: string = file.originalname.substr(0, file.originalname.lastIndexOf('.'))
                const name = currentFileName.toLowerCase().split(' ').join('-')
                const ext = MIME_TYPE_MAP[file.mimetype]
                callback(null, `${name}-${Date.now()}.${ext}`)
            }
        })
    }
}

export const ImageStorage = new ImageStorageService().storage

然后在你的路线之一

import { ImageStorage } from "./services/image-storage.service";

this.router.post('/signup', multer({ storage: ImageStorage }).single('image'), async (req, res, next) => {
    let img_url: string
    if (req.file) {
        const url: string = `${req.protocol}:\/\/${req.get('host')}`
        img_url = url + '/images/' + req.file.filename
        //http://localhost:3000/images/penguins-1548339248380.jpg
    }
})
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}`);
  }
});

编辑

shortid 已被弃用,您应该使用 nanoid。

import multer from 'multer';
import * as nanoid from 'nanoid';
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 = nanoid();
    /* 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}`);
  }
});

文件扩展名可以是动态的。 这是解决方案

const path = require('path'); // path for cut the file extension
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads')
    },
    filename: function (req, file, cb) {
      cb(null, 'upload_at_' + Date.now() + path.extname(file.originalname))
    }
  })

出于 SEO 目的,我喜欢使用原始文件名。这需要更多地检查同名文件是否已经存在。 此外,分几步完成扩展解析以提供最大的灵活性。

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 });

我用这个方法,效果很好。

我以这种格式存储文件: 字段名+日期+扩展名=> Profile1621416613594.jpg

var multer = require('multer');
    
var storage = multer.diskStorage({
    destination: function (req,file,cb){
        cb(null, './uploads')
    },
    filename: function (req,file,cb){
        cb(null,file.fieldname+'-'+Date.now()+'.'+file.mimetype.split('/').reverse()[0]);
    },
});

var upload = multer({storage: storage}); 

可以这样...简单掌握

// validate uploaded files
const FILE_TYPE_MAP = {
  // mime type
  "image/png": "png",
  "image/jpeg": "jpeg",
  "image/jpg": "jpg",
};
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads");
  },
  filename: function (req, file, cb) {
    const filename = file.originalname.replace(" ", "-");
    const extension = FILE_TYPE_MAP[file.mimetype]
    cb(null, `${filename}-${Date.now()}.${extension}`);
  },
});

const multer = require('multer');
const uuid = require('uuid/v1');

const MIME_TYPE_MAP = {
  'image/png': 'png',
  'image/jpeg': 'jpeg',
  'image/jpg': 'jpg'
};

const fileUpload = multer({
  limits: 500000,
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, 'uploads/images');
    },
    filename: (req, file, cb) => {
      const ext = MIME_TYPE_MAP[file.mimetype];
      cb(null, uuid() + '.' + ext);
    }
  }),
  fileFilter: (req, file, cb) => {
    const isValid = !!MIME_TYPE_MAP[file.mimetype];
    let error = isValid ? null : new Error('Invalid mime type!');
    cb(error, isValid);
  }
});

module.exports = fileUpload;

const multer = require('multer'); const uuid = require('uuid/v1');

const MIME_TYPE_MAP = {
  'image/png': 'png',
  'image/jpeg': 'jpeg',
  'image/jpg': 'jpg'
};

const fileUpload = multer({
  limits: 500000,
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, 'uploads/images');
    },
    filename: (req, file, cb) => {
      const ext = MIME_TYPE_MAP[file.mimetype];
      cb(null, uuid() + '.' + ext);
    }
  }),
  fileFilter: (req, file, cb) => {
    const isValid = !!MIME_TYPE_MAP[file.mimetype];
    let error = isValid ? null : new Error('Invalid mime type!');
    cb(error, isValid);
  }
});

module.exports = fileUpload;

维护 multer 生成的唯一文件名并添加从 mimetype 解析的扩展名的简单辅助函数:

只传multer返回的对象


const fs = require('fs');

function renameWithExt(file) {
  const ext = file.mimetype.split('/')[1]; // parse the extension type

  fs.rename(`${file.path}`, `${file.path}.${ext}`, () => {
    console.log(`File: ${file.filename} renamed with extension '.${ext}'`);
  });
}

renameWithExt(req.file);