我是节点新手。我只想在POST请求中传递值,例如上传文件。这是我的示例代码:

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

 var bodyParser = require('body-parser');
 var urlencodedParser = bodyParser.urlencoded({ extended: false });

 var multer  = require('multer');
 var upload = multer({ dest: '/tmp/'});
 app.use(express.static('public'));
 app.post('/process_post', urlencodedParser, function (req, res) {
    console.log(req.files.file.name);

    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:'Save successfully',
                    first_name:req.body.firstname,
                    last_name:req.body.lastname,
                    filename:req.files.file.name
              };
         }
         console.log( response );
         res.end( JSON.stringify( response ) );
       });
    });
  })


HTML:

 <html>
     <body>
             <form action="http://127.0.0.1:8081/process_post" method="POST" enctype="multipart/form-data">
        First Name: <input type="text" name="firstname">
        <br>
        Last Name: <input type="text" name="lastname">
        <br>
        Picture: <input type="file" name="file" size="50" />
        <br>
        <input type="submit" value="Submit">
    </form>
</body></html>


req.files始终是未定义的。
提前致谢!

最佳答案

您正在require正在multer,但不要配置或使用它。从文档:

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

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

10-02 03:25