Multer正在上传文件,但未填充req.files

时间:2018-07-22 23:37:55

标签: node.js express multer

我正在为一个学校项目研究node.js,但我不知道为什么我的代码无法正常工作。每当我上传包含文本和文件的表单时,都会填充req.body,但不会填充

server.js

const multer = require('multer')
const bparser = require('body-parser')

app.use(bparser.urlencoded(settings.body_parser))
...
let multer_storage = multer.diskStorage({
    destination: (req, file, cb) => { 
        cb(null, path.join(__dirname, settings.multer.destination))
    },
    filename: (req, file, cb) => {
        cb(null, Date.now() + path.extname(file.originalname))
    }
})

let multer_options = {
    storage: multer_storage,
    fileFilter: (req, file, cb) => {
        if (settings.multer.allowed_files.indexOf(file.mimetype) >= 0) 
            cb(null, true)

        cb(null, false)
    }
}

app.use(multer(multer_options).any())

app.use("*", (req, res, next) => {

    if (!req.session.user)
        if (req.cookies.user)
            req.session.user = req.cookies.user

    next()
})

for (let i = 0; i < settings.routes.length; i++) {
    app.use('/', require("./core/routers/" + settings.routes[i]))
}
...

./ core / routers / post.js

const router = require('express').Router()
...
router.post('/post/share/', (req, res) => {

    let data = {
        title: req.body.title,
        user: req.session.user,
        post: req.files[0].path,
        tags: req.tags.split(" ")
    }

    post.create(data).then((result) => {
        return result
    })
})

我一直遇到“ TypeError:无法读取未定义的属性'path'”

2 个答案:

答案 0 :(得分:0)

当您在cb(null, false)方法中调用fileFilter时,您告诉multer不应处理该文件,但它仍将进入中间件,其中req.files为{{1 }}这就是为什么您会收到该错误。

如果文件没有被处理,如果您不希望它进入中间件,那么您应该将错误传递给回调:

undefined

在任何情况下,您都会在let multer_options = { storage: multer_storage, fileFilter: (req, file, cb) => { if (settings.multer.allowed_files.indexOf(file.mimetype) >= 0) return cb(null, true); // this return is missing cb(new Error('Invalid file')); } } 之前丢失return语句,否则您将调用两次回调,一次使用cb(null, true);,另一次使用true


总而言之,如果您没有将false传递给Error函数,则应检查中间件中是否存在fileFilter

答案 1 :(得分:0)

或者您可以尝试以下代码:

library(raster)
library(rasterVis)

r1 <- raster(matrix(runif(100), 10))
r2 <- as.factor(raster(matrix(rbinom(100, 1, 0.8), 10)))
levels(r2)[[1]]$name <- c('gray', 'lightblue')

p1 <- levelplot(r1, margin=FALSE, scales=list(draw=FALSE), 
                at=seq(0, 1, length.out=100))
p2 <- levelplot(r2, scales=list(draw=FALSE), 
                col.regions=c('gray90', 'lightblue'))

print(p1, split=c(1, 1, 1, 2), more=TRUE)
print(p2, split=c(1, 2, 1, 2))