How to upload file using multer or body-parser

后端 未结 4 1899
感动是毒
感动是毒 2021-01-17 12:34

I am a NodeJS beginner, following along a book \"Web Development with MongoDB and NodeJS\". I am stuck at its chapter 6 with \'multer\'. When I use multer for file uploads t

4条回答
  •  一向
    一向 (楼主)
    2021-01-17 12:57

    Code for upload file using Multer and save it to local folder

    api- call fileUpload function
    fileUpload(req)
        .then(uploadRes => {
            console.log('uploadRes', uploadRes)
        })
        .catch(err => {
            console.log('err', err)
        })
    
    
    Create file upload service
    const multer = require('multer') // import library
    const moment = require('moment')
    const q = require('q')
    const _ = require('underscore')
    const fs = require('fs')
    let dir = './public'
    
    /** Store file on local folder */
    let storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, dir)
        },
        filename: function (req, file, cb) {
            let date = moment(moment.now()).format('YYYYMMDDHHMMSS')
            cb(null, date + '_' + file.originalname.replace(/-/g, '_').replace(/ /g, '_'))
        }
    })
    
    /** Upload files */
    let upload = multer({ storage: storage }).array('files')
    
    /** Exports fileUpload function */
    module.exports = {
        fileUpload: function (req) {
            let deferred = q.defer()
    
            /** Create dir if not exist */
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir)
                console.log(`\n\n ${dir} dose not exist, hence created \n\n`)
            }
    
            upload(req, {}, function (err) {
                if (req && (_.isEmpty(req.files))) {
                    deferred.resolve({ status: 200, message: 'File not attached', data: [] })
                } else {
                    if (err) {
                        deferred.reject({ status: 400, message: 'error', data: err })
                    } else {
                        deferred.resolve({
                            status: 200,
                            message: 'File attached',
                            filename: _.pluck(req.files,
                                'filename'),
                            data: req.files
                        })
                    }
                }
            })
            return deferred.promise
        }
    }
    

提交回复
热议问题