I am posting a file to a node server, it gives me a 404 status error

My HTML file is like the following,

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>file</title>
</head>
<body>
<form method="post" action="/getusrfile" enctype='multipart/form-data'>
    <input type="file" name="fil" >
    <button type="submit">
        sub
    </button>
</form>
</body>
</html>

      

I am using node, express this:

app.post("/getusrfile",function(req,res){
    console.log("came to server");// prints this
    console.log(req.files);//prints undefined
    //console.log(JSON.stringify(req.files.fil));
    fs.readFile(req.files.fil, function (err, data) {
        // ...
        var newPath = __dirname + "/../public/uploadedFileName";
        fs.writeFile(newPath, data, function (err) {
            console.log(err);
            res.send(err);
        });
    });
});

      

It is outputted to the server, but no file / directory is created on the server. And the response is "Can not POST / getusrfile" with a 404 status.

and req.files prints undefined

How do I make it work?

+3


source to share


1 answer


The first

    $ npm install --save multer

      

Then add the multer middleware before the app.post function:



    app.use(require('multer')({dest : __dirname }));

    app.post("/getusrfile",function(req,res){
      var filePath = req.files.fil.path;
      fs.readFile(filePath, function (err, data) {
        // ...  
      });
    });

      

Test:

   it('should respond "OK 200" to POST request with file payload',function(done){

        var filePath = path.join(__dirname,'test.txt');

        request(app)
        .post('/getusrfile')
        .attach('fil',filePath)
        .expect(200)
        .end(function(err,res){
            expect(err).to.not.exist;
            done();
        });
    });

      

0


source







All Articles