How to store a file with file extension with multer?

后端 未结 11 1606
情话喂你
情话喂你 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:29

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

提交回复
热议问题