设置:
nginx
和multer
扩展到50mb症状:
当通过http POST调用发送字符串化JSON数据和图像的混合时,服务器通过multer(multer.any()
)接收随机数量的图像。文件已上载并存在于服务器的公用文件夹中。 req.body
也行,但不知怎的,我无法访问req.files
。它返回undefined
。从heroku和我的桌面localhost,该应用程序运行正常。图像上传OK,访问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})
})
问题解决了。我已经从extended
将extended:false
选项改为app.use(bodyParser.urlencoded({limit:'50mb', extended:true}))
,现在它就像魔法一样。我从某个地方读到extended
的bodyParser
选项将其余的http请求数据转换为其他格式,所以我改变了它,现在它可以工作了。