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

Cri*_*alu 0 javascript multipartform-data node.js angularjs multer

我如何uploadYear将 Angular 服务传递到 Multer 目的地以获得动态路径,例如“./public/uploads/”+uploadedYear?

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

基本上我看不到myfile从前端到后端的路径,或者我如何在后端访问它。

角度服务

    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 }
        })
    }
Run Code Online (Sandbox Code Playgroud)

应用程序接口

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 })
            }
    })
})
Run Code Online (Sandbox Code Playgroud)

Fet*_*rij 6

您可以将其作为标题中的参数发送:

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

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