简体   繁体   English

无法在node.js中发布

[英]Cannot post in node.js

I want to upload file using node.js , being new to it a tried to check if the file is being send to server. 我想使用node.js上传文件,这是它的新手,试图检查文件是否正在发送到服务器。 html HTML

  <html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="img" method="POST" 
      enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>

js JS

var express  = require("express");
var app=express();
var http=require("http").Server(app);


app.get("/",function(req,res){
    res.end("hello")
});

app.get("/upload",function(req,res){
    res.sendFile(__dirname + "/form.html")
})
app.post("/img",function(req,res){
    if(req.files){
     console.log(req.files.file.name);
    }
    else{
        console.log("ee")
    }


});
http.listen(3000,function(){
    console.log("listening on 3000")
})

When i upload something , it throws error 当我上传东西时,它会引发错误

Cannot read files of undefined 无法读取未定义的文件

Being new to back end i have no idea why its happening , why doesnt the server recieve the file? 作为后端的新手,我不知道为什么会这样,服务器为什么不接收文件?

You need to app.use() a fileparser. 您需要app.use()一个文件app.use() For example, you could use connect-busboy . 例如,您可以使用connect-busboy You can get more information about options and usage at above link; 您可以在上面的链接中获得有关选项和用法的更多信息。 a simple setup would be somehting like this: 一个简单的设置就是这样:

var busboy = require('connect-busboy');
app.use(busboy());

app.post("/img",function(req,res){
        req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
            // ...
        });
        req.busboy.on('field', function (key, value, keyTruncated, valueTruncated) {
            // ...
        });
        req.pipe(req.busboy);
        // etc ...
});

As stated in the above answer, you must use a body parser for multipart bodies, but the better solution is to use the express middleware multer which lets you to use req.files just like in your OP. 如以上答案中所述,您必须对多部分主体使用主体解析器,但是更好的解决方案是使用快速中间件multer ,它使您可以像在OP中一样使用req.files

Also, multer is built on top of busboy which is the fastest multipart body parser for node.js 此外,multer建立在busboy之上,而busboy是node.js最快的多部分主体解析器

With multer: 与multer:

var express = require('express'),
    multer = require("multer"),
    app = express();

app.use(multer({
    dest: path.resolve(__root + path.sep + config.get("localFolders").rawImages),
    limits: {
         files: 2
    }
}));

// handle file upload
app.post("/img", function (req, res, next) {
    var image = req.files.image;
    // do something with image;
    console.log(image.name);
});

Have a look on the documentation for multer within the link provided above. 在上面提供的链接中查看有关multer的文档。 Good luck. 祝好运。 :) :)

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

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