javascript - 将图片上传到未定义的Node.js图片

标签 javascript node.js express file-upload

不好意思缩进
我是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);




按照this,req.files是图像文件,req.body是文件名
所以我用fs.readFile读取文件



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



4.than我需要一个文件路径和文件名,我使用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:无法读取未定义的属性“图像”

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)

最佳答案

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

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"});
          }
       });
    });
  };

关于javascript - 将图片上传到未定义的Node.js图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35628540/

相关文章:

mysql - 在 Node 中查询mysql后,res.render无法获取结果参数

javascript - 如何根据先前的下拉选择值填充下拉列表

node.js - 为什么 bin/www 命令在我的 cloud9 (c9) 新运行配置中不起作用?

javascript - 如果文件有任何更改,则在 node.js 中热重载外部 js 文件

node.js - 将 node_modules 安装到 vendor

node.js - Node + Redis + PHP 获取实时问题

node.js - 平均堆栈中的 session 处理

string - 要求文件为字符串

javascript - 为什么 ReactDOM.render 需要在创建虚拟 DOM 后再次调用函数或类组件?

javascript - 在Chrome浏览器中,尝试刷新同一窗口中其他框架的一个框架