How to store a file with file extension with multe

2019-03-11 02:35发布

问题:

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?

回答1:

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



回答2:

Sorry, I cannot comment on the Scott's answer above but 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 });


回答3:

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


回答4:

In 2018, it is done done like this:

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


回答5:

I used this little trick to get file extension, and as a workaround to circumvent issues that might occur when someone uploads a file with similar file name twice, or that exists in the server.

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 = file.originalname.split('.')[1]
        cb(null, customFileName + '.' + fileExtension)
    }
  })
})


回答6:

There may be some issues in the already answered codes.

  • There may be some cases of files with no extension.
  • There should not be an upload.any() usage. Its vulnerable to the attackers
  • The upload function should not be global .

I have written the below codes for better security.

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 it for upload

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


回答7:

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


回答8:

An object oriented way to store image with unique name

// 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

then in one of your routes

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