nodejs表达和文件上传

时间:2011-06-16 02:20:00

标签: file-io node.js express

好的,所以我已经尝试过使用连接形式了,但由于某些原因我无法让它工作,但我想我应该理解这是如何从头开始半无论如何。

我不明白我上传的multipart / formdata文件的位置,或者我的应用程序在发布到网址时如何访问它。 - 我喜欢直接访问文件数据,并使用节点fs模块写入文件输出。 - 例如:

    app.post('/testy', function(req, res){
       console.log(req.body);
       console.log(req.headers);
       res.redirect('back');

    });  

    app.get('/testy', function(req, res){
      res.send('<form method="post" action="/testy" enctype="multipart/form-data">'
        + '<p>Image: <input type="file" name="test" /></p>'
        + '<p><input type="submit" value="Upload" /></p>'
        + '</form>');
    });

因此,实际记录的唯一req var是req标头,body为空。 (可能应该是我理解的)。但我得到的是文件数据在哪里?寻找我想的$ _FILES数组的php等价物。 - 这是我记录的标题。

'accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-language': 'en-us,en;q=0.5',
'accept-encoding': 'gzip,deflate',
'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'keep-alive': '115',
connection: 'keep-alive',
referer: 'http://127.0.0.1:3000/testy',
cookie: 'connect.sid=lDRpluTxjUJeuTmkXlybrYeZ.JYTB155s2DGce2dsyfv1Op5ISCY8uqyqJZK8NjlZ5jM; socketio=flashsocket',
'x-insight': 'activate',
'content-type': 'multipart/form-data; boundary=---------------------------5856401949371863571646035001',
'content-length': '30128' }

任何关于我所遗失的东西的光芒总是非常值得赞赏!

3 个答案:

答案 0 :(得分:11)

这是非常详细的版本,没有连接形式。正如你所看到的,这不是有效的,而是试图对它如何运作起到指导作用。

var express = require('express'),
    fs = require('fs');
    app = express.createServer();

app.post('/testy', function(req, res){
  var body = '';
  var header = '';
  var content_type = req.headers['content-type'];
  var boundary = content_type.split('; ')[1].split('=')[1];
  var content_length = parseInt(req.headers['content-length']);
  var headerFlag = true;
  var filename = 'dummy.bin';
  var filenameRegexp = /filename="(.*)"/m;
  console.log('content-type: ' + content_type);
  console.log('boundary: ' + boundary);
  console.log('content-length: ' + content_length);

  req.on('data', function(raw) {
    console.log('received data length: ' + raw.length);
    var i = 0;
    while (i < raw.length)
      if (headerFlag) {
        var chars = raw.slice(i, i+4).toString();
        if (chars === '\r\n\r\n') {
          headerFlag = false;
          header = raw.slice(0, i+4).toString();
          console.log('header length: ' + header.length);
          console.log('header: ');
          console.log(header);
          i = i + 4;
          // get the filename
          var result = filenameRegexp.exec(header);
          if (result[1]) {
            filename = result[1];
          }
          console.log('filename: ' + filename);
          console.log('header done');
        }
        else {
          i += 1;
        }
      }
      else { 
        // parsing body including footer
        body += raw.toString('binary', i, raw.length);
        i = raw.length;
        console.log('actual file size: ' + body.length);
      }
  });

  req.on('end', function() {
    // removing footer '\r\n'--boundary--\r\n' = (boundary.length + 8)
    body = body.slice(0, body.length - (boundary.length + 8))
    console.log('final file size: ' + body.length);
    fs.writeFileSync('files/' + filename, body, 'binary');
    console.log('done');
    res.redirect('back');
  })
});  

app.get('/testy', function(req, res){
  res.send('<form method="post" action="/testy" enctype="multipart/form-data">'
           + '<p>Image: <input type="file" name="test" /></p>'
           + '<p><input type="submit" value="Upload" /></p>'
           + '</form>');
});

app.listen(4000);

答案 1 :(得分:4)

如何从示例库运行此代码段?

https://github.com/visionmedia/express/blob/master/examples/multipart/app.js

/**
 * Module dependencies.
 */

var express = require('express')
  , form = require('connect-form');

var app = express.createServer(
  // connect-form (http://github.com/visionmedia/connect-form)
  // middleware uses the formidable middleware to parse urlencoded
  // and multipart form data
  form({ keepExtensions: true })
);

app.get('/', function(req, res){
  res.send('<form method="post" enctype="multipart/form-data">'
    + '<p>Image: <input type="file" name="image" /></p>'
    + '<p><input type="submit" value="Upload" /></p>'
    + '</form>');
});

app.post('/', function(req, res, next){

  // connect-form adds the req.form object
  // we can (optionally) define onComplete, passing
  // the exception (if any) fields parsed, and files parsed
  req.form.complete(function(err, fields, files){
    if (err) {
      next(err);
    } else {
      console.log('\nuploaded %s to %s'
        ,  files.image.filename
        , files.image.path);
      res.redirect('back');
    }
  });

  // We can add listeners for several form
  // events such as "progress"
  req.form.on('progress', function(bytesReceived, bytesExpected){
    var percent = (bytesReceived / bytesExpected * 100) | 0;
    process.stdout.write('Uploading: %' + percent + '\r');
  });
});

app.listen(3000);
console.log('Express app started on port 3000');

npm install express
npm install connect-form
node app.js

对我来说很好......

答案 2 :(得分:1)

我能够让连接形式的包最终运行,菜鸟错误但是,如果你使用快递,请确保告诉应用程序在配置功能app.configure中使用表单模块(function(){ app.use(form({keepExtensions:true}));

(在帖子中它将在files.yourfileuploadfieldname.filename变量中)

- 据说,我仍然有兴趣知道如何从头开始,没有连接形式,如果它不难解释。