发送后无法发送标头。文件上传,异步问题?

时间:2015-10-08 13:22:18

标签: node.js express formidable

我正在使用ajax,nodejs,express和强大的模块开发多文件上传功能。

但是我有时从错误堆栈跟踪中得到错误Can't set headers after they are sent.,这是因为行return res.send({ status: 'success', files: files['upload']

我尝试检查可以多次发送的内容,并且我包含了一个计数器,以确保在上传所有文件后它会被触发一次,但有时仍会出现错误。

var express     = require('express'),
    router      = express.Router(),
    formidable  = require('formidable'),
    util        = require('util'),
    fs          = require('fs'),
    form        = new formidable.IncomingForm(),
    path        = require('path'),
    nodeHomeDir = path.dirname(require.main.filename);

form.type = 'multipart';
form.multiples = true;
form.maxFieldsSize = 52428800;
form.uploadDir = nodeHomeDir + '/tmp';
form.keepExtensions = true;

/* POST to /files to upload or delete files */
router.post('/', function (req, res, next) {

  form.parse(req, function (err, fields, files) {
    if (!files['upload'][0]) return res.send({ status: 'fail', message: 'No files provided.' });

    req.on('aborted', function () {
      return res.send({ message: 'fail' });
    });

    var webinarID     = fields.webinarID,
        uploadDirName = nodeHomeDir + '/webinarFiles/' + webinarID,
        filesLength   = Object.keys(files['upload']).length,
        counter       = 0;

    if (!webinarID) return res.send({ status: 'fail', message: 'No webinar ID provided.' });

    if (!fs.existsSync(uploadDirName)) {
      fs.mkdirSync(uploadDirName);
    }

    for (file in files['upload']) {
      if (files['upload'][file] && files['upload'][file].path && files['upload'][file].name) {
        var stream = fs.createReadStream(files['upload'][file].path).pipe(fs.createWriteStream(uploadDirName + '/' + files['upload'][file].name));
        stream.on('finish', function () {
          counter++;
          if (counter === filesLength) {
            // deleteFilesFromFolder(nodeHomeDir + '/tmp');
            return res.send({ status: 'success', files: files['upload'] });
          }
        });
      }
    }

  });

});

1 个答案:

答案 0 :(得分:0)

尝试这个:

    var async = require('async');
    async.eachSeries(files['upload'], function(elem,asynccallback){
     if (files['upload'][file] && files['upload'][file].path && files['upload'][file].name) {
            var stream = fs.createReadStream(files['upload'][file].path).pipe(fs.createWriteStream(uploadDirName + '/' + files['upload'][file].name));
            stream.on('finish', function () {
              counter++;
              if (counter === filesLength) {
                // deleteFilesFromFolder(nodeHomeDir + '/tmp');
                return res.send({ status: 'success', files: files['upload'] });
              }
            });
          }
    asynccallback();
});