从前端传递数据以创建动态 multer 目标文件夹

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

如何将 uploadYear 从 Angular 服务传递到 Multer 目的地,以便拥有动态路径,例如 './public/uploads/' + uploadedYear?

multer 的工作方式对我来说似乎很扭曲,我无法弄清楚在哪里存储额外的对象以便它可以一直到达 Multer 目的地。

基本上我看不到 myfile 如何从前端到后端或如何在后端访问它的踪迹。

Angular 服务

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

您可以将其作为参数发送到 header:

 $http.post('/api/uploadCV', fd, {
            transformRequest: angular.identity,
            headers: { 
              'Content-Type': undefined,
              'path': uploadYear
            }
        });

然后在你的后端你可以通过req.headers.path

得到它