![](/img/trans.png)
[英]nodejs req.on('end', callback) doesn't work property
[英]MEAN: A file uploaded ignores completely the req.on() NodeJS method
我正在使用MEAN.IO開發Webapp。
目前,我正在嘗試完成圖像的上傳器。 為此,我正在使用angular-file-upload,它似乎工作得很好。
我的問題是在服務器端。 我有這樣的事情:
exports.upload = function(req, res, next) {
console.log(root.process.env.PWD); // OK
var uploadPath = path.normalize(root.process.env.PWD + '/uploads'),
file = req.files.file, // file itself
data = new Buffer(''),
imgURL = undefined; // public URL to show the pic
console.log(file.name); // OK
console.log(file.path); // OK
console.log(uploadPath); // OK
if( !fs.existsSync(uploadPath) ){
console.log('Creating directory.');
fs.mkdirSync(uploadDir, 0755);
}
req.on('data', function(chunk) {
console.log('Receiving data');
data = Buffer.concat( [data, chunk] );
})
.on('end', function() {
console.log('Data received');
// Writing file to hard disk
fs.writeFile(uploadPath, data, function(err) {
if ( err ) {
console.log('Error saving the uploaded header image.');
return res.status(500).json({
error: 'Cannot upload the image'
});
}
console.log('Header image properly uploaded and saved.')
// Creating the public URL to send it out
imgURL = '/uploads/' + file.name;
console.log(imgURL);
res.json(imgURL);
});
});
console.log('Finished');
};
當我在console.log中添加//注釋時,是因為它打印了必須打印的內容(因此可以正常工作)。
我的主要問題是
console.log('Receiving data');
和
console.log('Data received');
沒有打印出來,因此執行流程完全忽略了兩個req.on()方法。 我毫不懷疑為什么,但是我敢肯定這一定是我已經忘記的東西。
該
console.log('Finished');
正確打印,因此執行完成沒有任何問題或異常。
提前致謝!
編輯:
在routes.js中,我添加了這個(我忘了提了):
'use strict';
var Media = require('../controllers/Media'),
multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var hasAuthorization = function(req, res, next) {
if (!req.user.isAdmin) {
return res.send(401, 'User is not authorized.');
}
next();
};
module.exports = function(Media, app, auth, database) {
app.route('/media/upload/header')
.post(multipartMiddleware, auth.requiresLogin, hasAuthorization, Media.upload);
};
好吧,我發現自己處於類似的情況,我只是忘了設置一個用於請求文件的中間件,在這種情況下, busboy做到了!
在您的快速配置中只需執行以下操作:
var busboy = require('connect-busboy');
然后
app.use(busboy());
在您的控制器中:
exports.upload = function(req, res) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file',function(fieldname, file, filename, encoding, mimetype){
console.log('uploading file:'+mimetype);
file.on('data',function(data){
});
file.on('end', function(){
});
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.