简体   繁体   English

使用express和multer无法在节点中运行node.js服务器上传文件

[英]Cannot run node.js server for upload file in node using express and multer

i'm just a beginner in node.js i'll try to make a site with xpress, so I can upload anything on there. 我只是node.js的初学者,我会尝试使用xpress建立一个网站,所以我可以在那里上传任何东西。 i set the server locally on my mac. 我在我的mac上本地设置服务器。

it is the code that I'd writen 这是我写的代码

server.js server.js

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

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

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

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

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

and these are the error messages 这些是错误消息

node upload.js 节点upload.js

/Users/dayatura/Documents/node/node_modules/express/lib/application.js:209 throw new TypeError('app.use() requires middleware functions'); /Users/dayatura/Documents/node/node_modules/express/lib/application.js:209抛出新的TypeError('app.use()需要中间件函数'); ^ ^

TypeError: app.use() requires middleware functions at EventEmitter.use (/Users/dayatura/Documents/node/node_modules/express/lib/application.js:209:11) at Object. TypeError:app.use()需要Object的EventEmitter.use(/Users/dayatura/Documents/node/node_modules/express/lib/application.js:209:11)中的中间件函数。 (/Users/dayatura/Documents/node/upload.js:10:5) (/Users/dayatura/Documents/node/upload.js:10:5)

at Module._compile (module.js:570:32) 在Module._compile(module.js:570:32)

at Object.Module._extensions..js (module.js:579:10) 在Object.Module._extensions..js(module.js:579:10)

at Module.load (module.js:487:32) 在Module.load(module.js:487:32)

at tryModuleLoad (module.js:446:12) 在tryModuleLoad(module.js:446:12)

at Function.Module._load (module.js:438:3) 在Function.Module._load(module.js:438:3)

at Module.runMain (module.js:604:10) 在Module.runMain(module.js:604:10)

at run (bootstrap_node.js:394:7) 在运行时(bootstrap_node.js:394:7)

at startup (bootstrap_node.js:149:9) 在启动时(bootstrap_node.js:149:9)

anyone help please :) 有人帮忙请:)

These are the issues: 这些是问题:

var multer  = require('multer')(({ dest: '/public/'}));

Then you can use it this way. 然后你就可以这样使用它。

app.post('/upload', multer.single('image'), function(req, res,next){
//Handle image content here.
console.log(req.file); //to access file
});

multer is meant to be used in the following way, per the docs: 根据文档,multer应按以下方式使用:

var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

Documentation regarding how to use any of the multer methods: https://github.com/expressjs/multer#usage 有关如何使用任何multer方法的文档: https//github.com/expressjs/multer#usage

I have just studied multer examples from above links. 我刚从上面的链接中研究过multer示例。

Js JS

var express = require('express');
var app     = express();
var fs      = require("fs");
var multers = require('multer');
var upload  = multers({ dest: '/public/'});

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

app.post('/file_upload', upload.array('avatar'), function (req, res) {

   for (var i = 0, len = req.files.length; i < len; i++) {
      var mainFile = req.files[i];
      var file = __dirname + "/" + mainFile.name;

      fs.readFile( mainFile.path, function (err, data) {
         fs.writeFile(file, data, function (err) {
            if( err ){
               console.log( err );
               }else{
                  response = {
                     message :'File uploaded successfully',
                     filename: mainFile.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)   
})

this is complete code to upload files using multer : 这是使用multer上传文件的完整代码:

var multer  = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
    cb(null, './public/app/product') /* here you define destination of uploaded files*/
},
filename: function (req, file, cb) {
    var ext=file.originalname.split(".")
    cb(null, Date.now() +'.'+ext[1]) /* here you set extensions of files when uploaded */
}
})
var upload = multer({ storage: storage });

/* upload.any() method upload any files */
app.post('/backend/product/edit/:id',upload.any(),function (req, res) {



/* req.files are all files that uploaded to server */ 
/* you can see them use res.json(req.files) */ 

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM