node.js文件上传typeError无法读取属性“图像" [英] node.js file upload typeError Can not read property 'image'

查看:87
本文介绍了node.js文件上传typeError无法读取属性“图像"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此程序示例将图像上传到uploads/fullsize目录中. 该应用程序正在运行,但是如果我尝试上传图像,则会出现以下故障:

TypeError:无法读取Object.handle上未定义的属性"image" (/Users/machupicchu/Desktop/test/app.js:46:23)在next_layer (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/route.js:103:13) 在Route.dispatch (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/route.js:107:5) 在c (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:195:24) 在Function.proto.process_params (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:251:12) 在下一个 (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:189:19) 在下一个 (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:166:38) 在下一个 (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:166:38) 在Layer.staticMiddleware [作为句柄] (/Users/machupicchu/Desktop/test/node_modules/express/node_modules/serve-static/index.js:55:61) 在trim_prefix (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:226:17)

该应用程序如下所示:

var express = require('express');
var bodyParser = require('body-parser');
var path = require ('path');
var port = 3000;
var fs = require('fs');


//var collection;
//dataExt = require('./routes/serverExtend');
// setup middleware
var app = express();
app.use(bodyParser());
app.use(express.static(__dirname + '/public')); //setup static public directory

app.set('views', __dirname + '/views'); //optional since express defaults to CWD/views
app.set('view engine', 'ejs');

// Start server
app.listen(port);
console.log('App started on port ' + port);


var form = "<!DOCTYPE HTML><html><body>" +
"<form method='post' action='/upload' enctype='multipart/form-data'>" +
"<input type='file' name='image'/>" +
"<input type='submit' /></form>" +
"</body></html>";

app.get('/', function (req, res){
    res.writeHead(200, {'Content-Type': 'text/html' });
    res.end(form);  
});

app.get('/uploads/fullsize/:file', function (req, res){
    file = req.params.file;
    var img = fs.readFileSync(__dirname + "/uploads/fullsize/" + file);
    res.writeHead(200, {'Content-Type': 'image/jpg' });
    res.end(img, 'binary');

});

/// Post files
app.post('/upload', function(req, res) {

    fs.readFile(req.files.image.path, function (err, data) {

        var imageName = req.files.image.name

        /// If there's an error
        if(!imageName){

            console.log("There was an error")
            res.redirect("/");
            res.end();

        } else {

          var newPath = __dirname + "/uploads/fullsize/" + imageName;

          /// write file to uploads/fullsize folder
          fs.writeFile(newPath, data, function (err) {

            /// let's see it
            res.redirect("/uploads/fullsize/" + imageName);

          });
        }
    });
});

有人可以帮我为什么我收到TypeError吗? 还创建了我的目录,文件应保存在该目录中. app.js 上传->全尺寸-> images.jpg

解决方案

由于body-parser不提供文件,因此您需要多部分中间件才能使文件上载.

首先,将其添加到您的应用程序顶部:

var multipart = require('connect-multiparty');

接下来,稍微修改您的发布路线:

app.post('/upload', multipart(), function(req, res) {
   // ... 
}

现在req.files现在应该可以在您的POST /upload路线上使用了.

I am using this program example to upload a image into uploads/fullsize directory. The application is running but if I try to upload a image I am getting the following failure:

TypeError: Cannot read property 'image' of undefined at Object.handle (/Users/machupicchu/Desktop/test/app.js:46:23) at next_layer (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/route.js:103:13) at Route.dispatch (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/route.js:107:5) at c (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:195:24) at Function.proto.process_params (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:251:12) at next (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:189:19) at next (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:166:38) at next (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:166:38) at Layer.staticMiddleware [as handle] (/Users/machupicchu/Desktop/test/node_modules/express/node_modules/serve-static/index.js:55:61) at trim_prefix (/Users/machupicchu/Desktop/test/node_modules/express/lib/router/index.js:226:17)

The application looks like this:

var express = require('express');
var bodyParser = require('body-parser');
var path = require ('path');
var port = 3000;
var fs = require('fs');


//var collection;
//dataExt = require('./routes/serverExtend');
// setup middleware
var app = express();
app.use(bodyParser());
app.use(express.static(__dirname + '/public')); //setup static public directory

app.set('views', __dirname + '/views'); //optional since express defaults to CWD/views
app.set('view engine', 'ejs');

// Start server
app.listen(port);
console.log('App started on port ' + port);


var form = "<!DOCTYPE HTML><html><body>" +
"<form method='post' action='/upload' enctype='multipart/form-data'>" +
"<input type='file' name='image'/>" +
"<input type='submit' /></form>" +
"</body></html>";

app.get('/', function (req, res){
    res.writeHead(200, {'Content-Type': 'text/html' });
    res.end(form);  
});

app.get('/uploads/fullsize/:file', function (req, res){
    file = req.params.file;
    var img = fs.readFileSync(__dirname + "/uploads/fullsize/" + file);
    res.writeHead(200, {'Content-Type': 'image/jpg' });
    res.end(img, 'binary');

});

/// Post files
app.post('/upload', function(req, res) {

    fs.readFile(req.files.image.path, function (err, data) {

        var imageName = req.files.image.name

        /// If there's an error
        if(!imageName){

            console.log("There was an error")
            res.redirect("/");
            res.end();

        } else {

          var newPath = __dirname + "/uploads/fullsize/" + imageName;

          /// write file to uploads/fullsize folder
          fs.writeFile(newPath, data, function (err) {

            /// let's see it
            res.redirect("/uploads/fullsize/" + imageName);

          });
        }
    });
});

Can someone help me why I am getting the TypeError?? Also created my directory where the files should be save. app.js uploads -> fullsize -> images.jpg

解决方案

You need multipart middleware for your file upload to work as body-parser does not provide it.

First, add this to the top of your app:

var multipart = require('connect-multiparty');

Next, edit your post route slightly:

app.post('/upload', multipart(), function(req, res) {
   // ... 
}

Now req.files should now be avaiable to you in your POST /upload route.

这篇关于node.js文件上传typeError无法读取属性“图像"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆