내 nodejs
express
app에 json 요청을 읽으려면 body-parser
, 파일 업로드에는 multer
을 사용하고 있습니다. 나는 항상 json에서 몇 가지 정보를 보내고 있는데, 그 이유는 사용자가 업로드 할 수 있는지 여부를 알아야하기 때문입니다. 테스트를 위해이 httpie
명령을 사용합니다.body-parser 및 multer reading multipart + json
http -vf POST localhost:9090/upload [email protected] id=638381
요청은 여러 미들웨어를 통과하지만, multer
이후에만 미들웨어 내가 req.body
에 대해 빈 JSON을 얻을 multer
전에 req.body.id
에 액세스 할 수 있습니다.
아래의 최소 예에서는 현재 gridfsUpload
만 ID를 볼 수 있지만, multer
을 위 또는 아래로 이동하면이 변경 사항이 적용됩니다.
var http = require('http');
var express = require('express')
var bodyParser = require('body-parser');
var argv = require('minimist')(process.argv.slice(2),{default:{port:8081}});
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
dir = __dirname+ '/tmp/'
cb(null, dir)
},
})
var app = express();
app.use(bodyParser.urlencoded({ extended: true,limit:'10mb' }));
app.use(bodyParser.json({limit: '10mb'}));
app.use((req,res,next) => {
console.log("body 1",req.body)
console.log("head 1",req.header)
next()
})
var gridfsUpload = function(options){
return function (req, res, next) {
console.log("body 2",req.body)
console.log("head 2",req.header)
res.end()
}
}
var checkrole_measurement = (options) => {
return function (req, res, next) {
console.log("body 3",req.body)
console.log("head 3",req.header)
next()
}
}
app.post('/upload',
checkrole_measurement(),
multer({ storage: storage }).any(),
gridfsUpload(),
function(req,res,next){
;
}
);
var httpServer = http.createServer(app);
httpServer.listen(argv['port']);
난 정말이 일이 안 것을 확인할 수 있습니다 때, 그렇지 않으면 권한이없는 사람이 파일을 업로드 할 수있는이 방법은 나중에, 내가 그것을 삭제해야하기 때문에 multer
전에 ID를 확인하고 싶습니다. 처음에 multer
에게 요청을 전달하지 않았다면 더 쉬울 것입니다.
1 :
대용량 파일을 업로드하면 요청 본문이 청크로 서버로 보내지 만 모든 내용이 한 번에 표시되지는 않습니다. 'multer'는 도착한 파일을 파일로 읽어 들일 것입니다. 요청 본문 *에 * 다른 파일이있는 경우 파일을 읽은 후에야 액세스 할 수있는 방법이 없습니다. 대부분의 경우 클라이언트가 이전 파일을 보내지 않을 수도 있습니다. 소비되었습니다. ID 대신 URL 또는 요청 헤더로 이동할 수 있으며, 본문 앞에 수신됩니다. – skirtle