【问题标题】:Upload image to Node.js image' of undefined将图像上传到未定义的 Node.js 图像'
【发布时间】:2016-02-25 21:33:03
【问题描述】:

抱歉缩进不佳 我是 node.js 的新手,正在尝试将图像上传到 node.js 检查很多答案,如果我错了,请纠正我

1.bodyParser 需要一个中间件来处理二进制文件,比如IMAGE 如果我不使用它,它会显示

undefine token

2.使用 Multer 作为中间件,像这样

var multer = require('multer') 

var upload = multer({ dest:'/Node/file-upload/uploads/' });

app.post('/upload',upload.array(),songs.upload);
  1. follow this,req.files是图片文件,req.body是文件名 所以我使用 fs.readFile 来读取文件
fs.readFile(req.files.image.path, function (err, data)

4.我需要一个文件路径和文件名,我使用req.body

var dirname = "/Node/file-upload/uploads/";

var newPath = dirname + req.body.image.filename;

5.than 将数据写入目的地

fs.writeFile(newPath, data, function (err)

我不确定我错过了哪一部分,我花了 10 个小时才做到这一点,请帮忙

它总是告诉我 TypeError: Cannot read property 'image' of undefined

app.js

var    express = require('express')
      ,bodyParser = require('body-parser')
      ,app = express()
      ,multer  =  require('multer')
      ,binary = require('binary')
      ,fs = require('fs')
      ,util= require('util')
      ,http = require('http')
      ,multer = require('multer')
      ,upload = multer({ dest: '/Node/file-upload/uploads/' });

 app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies.
 app.use(bodyParser.json({limit: '5mb'}));


songs = require('./routes/route');

app.listen(3000, function () {
      console.log('Example app listening on port 3000!');
                          });
app.post('/upload',upload.array(),songs.upload);

route.js

var mongoose = require('mongoose');
var uri = "mongodb://xxxxxx:xxxxxxx@ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var binary = require('binary');
var body = require('body-parser');
var fs = require('fs');

db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));

db.once('open', function() {
     console.log("mongodb is connected!!");
 });

exports.upload = function(req, res) {
    console.log(req.body);
       fs.readFile(req.files.image.path, function (err, data){
            var dirname = "/Node/file-upload/uploads/";
            var newPath = dirname + req.body.image.filename;
       fs.writeFile(newPath, data, function (err) {
            if(err){
                res.json({'response':"Error"});
            }else {
                res.json({'response':"Saved"});
          }
       });
    });
  };

错误

TypeError: Cannot read property 'image' of undefined
at exports.upload (c:\Users\awei\WebstormProjects\untitled\routes\girlshanlder.js:92:26)
at Layer.handle [as handle_request] (c:\Users\awei\node_modules\express\lib\router\layer.js:95:5)
at next (c:\Users\awei\node_modules\express\lib\router\route.js:131:13)
at multerMiddleware (c:\node_modules\multer\lib\make-middleware.js:18:41)
at Layer.handle [as handle_request] (c:\Users\awei\node_modules\express\lib\router\layer.js:95:5)
at next (c:\Users\awei\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (c:\Users\awei\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (c:\Users\awei\node_modules\express\lib\router\layer.js:95:5)
at c:\Users\awei\node_modules\express\lib\router\index.js:277:22
at Function.process_params (c:\Users\awei\node_modules\express\lib\router\index.js:330:12)
at next (c:\Users\awei\node_modules\express\lib\router\index.js:271:10)
at jsonParser (c:\Users\awei\node_modules\body-parser\lib\types\json.js:107:37)
at Layer.handle [as handle_request] (c:\Users\awei\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (c:\Users\awei\node_modules\express\lib\router\index.js:312:13)
at c:\Users\awei\node_modules\express\lib\router\index.js:280:7
at Function.process_params (c:\Users\awei\node_modules\express\lib\router\index.js:330:12)

【问题讨论】:

    标签: javascript node.js express file-upload


    【解决方案1】:

    你的app.js中的upload.array()应该是

    upload.array('image',1) // 1 here is number of files you would upload
    

    在你的 songs.upload 中间件中你会得到 req.files.image 作为一个数组,

    因此,您最好检查数组的长度并对其进行迭代以保存每个文件,或者如果您只想保存 1 个文件,您可以执行以下操作。

    例子:

    app.js

    app.post('/upload',upload.array('image',1),songs.upload);
    

    route.js

    var mongoose = require('mongoose');
    var uri = "mongodb://xxxxxx:xxxxxxx@ds061365.mongolab.com:61365/aweitest";
    mongoose.connect(uri);
    // we're connected!
    var db = mongoose.connection.db;
    var BSON = require('bson').BSONPure;
    var binary = require('binary');
    var body = require('body-parser');
    var fs = require('fs');
    
    db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
    
    db.once('open', function() {
         console.log("mongodb is connected!!");
     });
    
    exports.upload = function(req, res) {
        console.log(req.body);
           fs.readFile(req.files.image[0].path, function (err, data){
                var dirname = "/Node/file-upload/uploads/";
                var newPath = dirname + req.body.image.filename;
           fs.writeFile(newPath, data, function (err) {
                if(err){
                    res.json({'response':"Error"});
                }else {
                    res.json({'response':"Saved"});
              }
           });
        });
      };
    

    【讨论】:

    • 感谢回复,我改了'app.post('/upload',upload.array(),songs.upload);'仍然在 'fs.readFile(req.files.image[0].path, function (err, data)' 处回复 'Cannot read property 'image' of undefined'
    • upload.array('image',1)
    • 顺便说一句,我使用 POSTMAN 来测试这个 api
    • 我检查了这个stackoverflow.com/questions/25461888/… 它将文件定义为 并且我使用邮递员检查标题是 Content-Type → Content-Type此内容 text/html 的 mime 类型; charset=utf-8 不知道怎么回事...
    • 我认为这是一个内容类型的问题,我会尽快解决这个问题stackoverflow.com/questions/35630837/…
    猜你喜欢
    • 2016-07-04
    • 2014-07-03
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 2017-01-18
    • 2013-05-22
    • 2021-12-10
    相关资源
    最近更新 更多