环境:
nginx
& multer
症状:
当通过http POST调用发送混合的字符串化JSON数据和图像时,服务器通过multer(multer.any()
)接收随机数量的图像。该文件已上载并存在于服务器的公用文件夹中。 req.body
也行,但不知怎的,我无法访问req.files
。它返回undefined
。从heroku和我的桌面localhost,该应用程序运行正常。图像上传正常,访问req.files
数据也没有问题。只有VPS / CentOS7服务器出现问题。
客户端(React / Superagent / Babel / Webpack)
import request from 'superagent'
request.post('/modwimg')
.query({
//some token and other info goes here
})
.accept('application/json')
.field('data',JSON.stringify(jsonData))
.attach('image',this.state.imagedata)
.attach('bannerimage',this.state.bannerimagedata)
.then((res)=>{
console.log('upload finished')
this.setState({goback:true})
})
.catch((err)=>{
})
服务器端
const bodyParser = require('body-parser')
const multer = require('multer')
const pubDir = path.join(__dirname, 'pub')
const storage = multer.diskStorage({
destination: (req,file,cb)=>{
cb(null,'pub/')
},
filename: (req,file,cb)=>{
cb(null,Date.now() + file.originalname)
}
})
const upload = multer({storage:storage})
//allowing public access, image goes to public dir
app.use('/pub', express.static(pubDir))
/* initialize bodyparser to build up RESTful app */
//file size limit expansion
app.use(bodyParser.urlencoded({limit:'50mb', extended:true}))
app.use(bodyParser.json({limit:'50mb'}))
app.post('/imageupload',upload.any(),(req,res,next)=>{
//some token approval goes here
console.log(req.files) // <----this returns undefined data, but image is still uploaded
console.log(req.body) // <---- this is fine!!
//putting data(JSON.parse(req.body)) to db
db.any( //....
)
//then respond to client
res.json({result:true})
})
答案 0 :(得分:0)
问题解决了。我已将extended
选项从extended:false
更改为app.use(bodyParser.urlencoded({limit:'50mb', extended:true}))
,现在它就像魔法一样。我从某处读到extended
的{{1}}选项将其余的http请求数据转换为其他格式,所以我已经更改了它,现在它可以正常工作。