文件上传程序给出错误

时间:2011-04-26 09:23:50

标签: file-upload node.js

运行此代码时

http://planetcakephp.org/aggregator/items/3241-streaming-file-uploads-with-nodejs

var http = require('http');
var multipart = require('./multipart');
var sys = require('sys');

var server = http.createServer(function(req, res) {
    console.log('in upload files'+req.url);

  switch (req.url) {
    case '/':
      display_form(req, res);
      break;
    case '/upload':
      upload_file(req, res);
      break;
    default:
      show_404(req, res);
      break;
  }
});
server.listen(8000);

function display_form(req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(
    '<form action="/upload" method="post" enctype="multipart/form-data">'+
    '<input type="file" name="upload-file">'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );

}

function upload_file(req, res) {
    console.log('in upload files');
  req.setEncoding('binary');

  var stream = new multipart.Stream(req);
  stream.addListener('part', function(part) {
    console.log('in upload files1');
    part.addListener('body', function(chunk) {
        console.log('in upload files2');
      var progress = (stream.bytesReceived / stream.bytesTotal * 100).toFixed(2);
      var mb = (stream.bytesTotal / 1024 / 1024).toFixed(1);

      sys.print("Uploading "+mb+"mb ("+progress+"%)\015");

      // chunk could be appended to a file if the uploaded file needs to be saved
    });
  });
  stream.addListener('complete', function() {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('Thanks for playing!');
    res.end();
    sys.puts("\n=> Done");
  });
}

function show_404(req, res) {
  res.writeHead(404, {'Content-Type': 'text/plain'});
  res.write('You r doing it rong!');
  res.end();
}

上传图片后出错:

reach121@youngib:~/rahul$ node test.js
in upload files/
in upload files/upload
in upload files

/home/reach121/rahul/test.js:37
  var stream = new multipart.Stream(req);
               ^
TypeError: undefined is not a function
    at CALL_NON_FUNCTION_AS_CONSTRUCTOR (native)
    at upload_file (/home/reach121/rahul/test.js:37:16)
    at Server.<anonymous> (/home/reach121/rahul/test.js:13:7)
    at Server.emit (events.js:67:17)
    at HTTPParser.onIncoming (http.js:1108:12)
    at HTTPParser.onHeadersComplete (http.js:108:31)
    at Socket.ondata (http.js:1007:22)
    at Socket._onReadable (net.js:678:27)
    at IOWatcher.onReadable [as callback] (net.js:177:10)

请说明为什么会出现此错误。

1 个答案:

答案 0 :(得分:0)

这是因为您使用的是旧教程。多部分显然已经改变了。

查看它的代码示例&gt; https://github.com/isaacs/multipart-js

或按照本教程&gt; http://www.componentix.com/blog/13