Thursday, 4 May 2017

Passing data from front-end to create a dynamic multer destination folder

How can i pass the uploadYear from the Angular Service to the Multer destination in order to have a dynamic path such as './public/uploads/' + uploadedYear?

The way multer works, seems very twisted to me and i'm incapable of figuring out where to store an extra object so it can make it all the way to the Multer Destination.

Basically i see no trails of how myfile travels from the front-end to the back-end or how can i access it on the back-end.

Angular Service

    this.uploadCV = function (file, uploadYear) {
        console.log(uploadYear)  //output 2017
        var fd = new FormData()
        fd.append('myfile', file.upload)
        return $http.post('/api/uploadCV', fd, {
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined }
        })
    }

API

var cv = ''
var CVstorage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/uploads')
    },
    filename: function (req, file, cb) {
        if (!file.originalname.match(/\.(jpg)$/)) {
            var err = new Error()
            err.code = 'filetype'
            return cb(err)
        } else {
            cv = file.originalname
            cb(null, cv)
        }
    }
})
var uploadCV = multer(
    {
        storage: CVstorage,
        limits: { fileSize: 10000000 } //limit 10 MB
    })
    .single('myfile')

//API Route
router.post('/uploadCV', function (req, res) {
    uploadCV(req, res, function (err) {
            if (!req.file) {
                //error handle
            } else {
                res.json({ success: true, cv: cv })
            }
    })
})



via Cristian Muscalu

No comments:

Post a Comment