简体   繁体   中英

I'm sending a file to node server it gives me 404 state error

My HTML file is like 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'm using node, express as following

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 prints came to server but no file/directory is created on the server. And the response is "Cannot POST /getusrfile" with status 404.

and req.files prints undefined

How to make it work?

First

    $ npm install --save multer

Then add multer middleware before 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();
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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