无法在Nodejs中执行fileupload程序

时间:2015-10-07 17:42:53

标签: javascript node.js single-page-application

我有一个简单的程序,我试图在http://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm的在线教程中执行,但我得到如下例外:

我对nodejs相对较新,我们非常感谢任何形式的帮助或指导。

使用NodeJS版本:4.1.1。

异常

TypeError: app.use() requires middleware functions
    at EventEmitter.use (c:\nital\my-data\my-sample-apps\nodejs\tutorialspoint-samples\node_modules\express\lib\application.js:209:11)
    at Object.<anonymous> (c:\nital\my-data\my-sample-apps\nodejs\tutorialspoint-samples\Sample37.js:11:5)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)
    at startup (node.js:117:18)
    at node.js:951:3

FileUploadDemo.js

var express = require('express');
var app = express();
var fs = require("fs");

var bodyParser = require('body-parser');
var multer = require('multer');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(multer({dest: 'C:/tmp/'}));

app.get('/upload.html', function (req, res) {
    res.sendFile(__dirname + "/" + "upload.html");
});

//uploading the file here
app.post('/file_upload', function (req, res) {
    console.log(req.files.file.name);
    console.log(req.files.file.path);
    console.log(req.files.file.type);

    var file = __dirname + "/" + req.files.file.name;
    fs.readFile(req.files.file.path, function (err, data) {
        fs.writeFile(file, data, function (err) {
            if (err) {
                console.log(err);
            } else {
                response = {
                    message: 'File uploaded successfully',
                    filename: req.files.file.name
                };
            }
            console.log(response);
            res.end(JSON.stringify(response));
        });
    });
});

var server = app.listen(8081, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log("Example app listening at http://%s:%s", host, port)
});

2 个答案:

答案 0 :(得分:2)

看起来multer的api已经改变了。由于本教程使用npm install multer --save,因此它会引入最新版本,而不是确保您拥有的版本兼容。有关如何使用它的详细信息,请参阅npm page。您现在似乎需要将特定中间件添加到特定路径中:

// Remove this line: app.use(multer({dest: 'C:/tmp/'}));
// Put this in instead
var upload = multer({ dest: 'C:/tmp/' });

// Change this: app.post('/file_upload', function (req, res) {
// to
app.post('/file_upload', upload.single('file'), function (req, res) {

虽然您可能仍然可以使用app.use将其添加到所有路由,但您肯定需要将其更改为使用upload.single(或他们选择的其他中间件)。

答案 1 :(得分:0)

这是我与nodejs教程不同的代码。

<强> server.js

//20160720 tested!
//[dif]:= different from http://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm

var express = require('express');
var app = express();
var fs = require("fs");

var bodyParser = require('body-parser');
var multer = require('multer');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
//[dif]app.use(multer({ dest: '/tmp/'}));
var upload = multer({ dest: '/tmp/'}); 


app.get('/index.htm', function (request, response) {response.sendFile( __dirname + "/" + "index.htm" );})

//[dif]app.post('/file_upload', function (request, response) {
app.post('/file_upload', upload.single('file'), function (request, response) {

/*[dif]
   console.log(request.files.file.name);
   console.log(request.files.file.path);
   console.log(request.files.file.type);
   var file = __dirname + "/" + request.files.file.name;
   fs.readFile( request.files.file.path, function (err, data) {
[dif]*/
   console.log(request.file.originalname);
   console.log(request.file.path);
   console.log(request.file.mimetype);


//[dif]   var file = __dirname + "/" + request.file.name;
   var file = __dirname + "/" + request.file.originalname;

   fs.readFile( request.file.path, function (err, data) {

        fs.writeFile(file, data, function (err) {
         if( err ){
              console.log( err );
         }else{
               uploadResponse = {
                   message:'File uploaded successfully',
//[dif]                   filename:request.files.file.name
                   filename:request.file.originalname

              };
          }
          console.log( uploadResponse );
          response.end( JSON.stringify( uploadResponse ) );
       });
   });
})

var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port

  console.log("Example app listening at http://%s:%s", host, port)
})

如果你收到错误 - &#34;错误:ENOENT:没有这样的文件或目录,打开&#39; C:\ tmp \ ce194372b624b45f2c881140fecad07f&#39;     在错误(本机)&#34; 您应该在根路径中创建tmp文件夹以保存临时文件。 在我的情况下是&#34; c:\ tmp&#34;和&#34; ce194372b624b45f2c881140fecad07f&#34;是临时文件。你应该在文件上传成功后删除它。