簡體   English   中英

我正在向節點服務器發送文件,它給我404狀態錯誤

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

我的HTML文件如下,

<!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>

我正在使用node,表達如下

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

它打印到服務器但在服務器上沒有創建文件/目錄。 並且響應是“不能POST / getusrfile”,狀態為404。

和req.files打印undefined

如何使它工作?

第一

    $ npm install --save multer

然后在app.post函數之前添加multer中間件:

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

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

測試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM