平均值:上传的文件完全忽略req.on()NodeJS方法

MEAN: A file uploaded ignores completely the req.on() NodeJS method

本文关键字:on req 方法 NodeJS 文件 平均值      更新时间:2023-09-26

我正在使用MEAN.IO开发Web应用程序。

此时此刻,我正试图完成一个图像上传程序。为此,我使用了angular文件上传,它似乎运行得很好。

我的问题出在服务器端。我有这样的东西:

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做到了!

在您的express配置中,只需执行以下操作:

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(){
        });
    });
};