无法在Nodejs中执行FileUpload程序

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

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

我无法使用NodeJS上传文件并获得以下异常。

例外:

TypeError: Cannot read property 'file' of undefined
    at c:\nital\my-data\my-sample-apps\nodejs\tutorialspoint-samples\Sample37.js:22:26
    at Layer.handle [as handle_request] (c:\nital\my-data\my-sample-apps\nodejs\tutorialspoint-samples\node_modules\express\lib\router\layer.js:95:5)
    at next (c:\nital\my-data\my-sample-apps\nodejs\tutorialspoint-samples\node_modules\express\lib\router\route.js:131:13)
    at Immediate.<anonymous> (c:\nital\my-data\my-sample-apps\nodejs\tutorialspoint-samples\node_modules\multer\lib\make-middleware.js:52:37)
    at Immediate.immediate._onImmediate (timers.js:431:18)
    at processImmediate [as _immediateCallback] (timers.js:374:17)

我在上面搜索了一下,发现http://expressjs.com/api.html#req

中提到的Express 4框架中不再提供req.files API

由于我是NodeJS的新手,不知道如何解决这个问题。有人可以指导吗?我的实际计划如下所列。

FileUploadDemo.js

//Express framework demo. File Upload demo
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}));
var upload = 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) {
app.post('/file_upload', upload.single('file'), 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)
});

1 个答案:

答案 0 :(得分:1)

由于您使用了upload.single(),因此可以通过req.file访问该文件,而不是req.files.file。如果您上传了多个文件(upload.array()或其他内容),则可以req.files访问该文件。