我想制作一个上传表单。这部分已经完成并且可以工作......但是现在我想在项目中使用相同的安全认证。
我有这个:
app.post('/me/profile/picture/upload',function(req, res){
req.form.on('part', function(part){
// transfer to s3 etc
console.log('upload %s %s', part.name, part.filename);
var out = fs.createWriteStream(tempUploadPath + part.filename);
part.pipe(out);
});
req.form.on('close', function(){
res.respond("Success!", 200);
});
});
但我想要这个:
app.post('/me/profile/picture/upload', passportToken.authenticate('bearer', { session: false }),function(req, res){
req.form.on('part', function(part){
// transfer to s3 etc
console.log('upload %s %s', part.name, part.filename);
var out = fs.createWriteStream(tempUploadPath + part.filename);
part.pipe(out);
});
req.form.on('close', function(){
res.respond("Success!", 200);
});
});
但是当我添加这个护照代码时,它会在传输文件时冻结。
答案 0 :(得分:0)
回调接收请求和响应对象作为参数。您必须将这些传递给身份验证功能。尝试这样的事情:
app.post('/me/profile/picture/upload', function (req, res) {
passportToken.authenticate('bearer', { session: false }), function(){
req.form.on('part', function(part){
// transfer to s3 etc
console.log('upload %s %s', part.name, part.filename);
var out = fs.createWriteStream(tempUploadPath + part.filename);
part.pipe(out);
});
req.form.on('close', function(){
res.respond("Success!", 200);
});
})(req, res)
});
答案 1 :(得分:0)
最终解决了!
需要添加:
app.use(express.bodyParser({
keepExtensions: true,
uploadDir: __dirname + '/tmp',
limit: '20mb'
}));
// Create our own middleware constructor.
var bufferedAuthenticate = function(){
// Set up standard authenticate handler passing arguments through.
var authMiddleware = passportToken.authenticate.apply(passportToken, arguments);
// Pass our own middleware instead that wraps passport-http.
return function(req, res, next){
// Pause the request before authenticating.
var obj = pause(req);
authMiddleware(req, res, function(err){
next(err);
// Emit any cached data events that fired while authenticating.
obj.resume();
});
};
};
app.post('/me/profile/picture/upload', bufferedAuthenticate('bearer', { session: false }), function (req, res) {
console.log(req.body);
if (req.files.qqfile) {
var exists = fs.existsSync(req.files.qqfile.path);
fs.rename(req.files.qqfile.path, "tmp/" + req.files.qqfile.name, function (err) {
if (err) {
console.log(">> Error!: " + err);
res.send(JSON.stringify({ success: false, error: err }), { 'Content-type': 'application/json' }, 200);
}
else {
console.log('File Uploaded! ' + "tmp/" + req.files.qqfile.name);
res.send(JSON.stringify({ success: true }), { 'Content-type': 'application/json' }, 200);
}});
} else {
res.send(JSON.stringify({ success: false, error: "No file sent!" }, { "Content-type": "application/json" }, 200));
}
});