简体   繁体   English

如何从NodeJS的客户端获取上传的文件?

[英]How to get uploaded file from clientside in NodeJS?

I'm using the npm multer module in my nodejs file to get formdata from the clientside, which contains the image that I upload from my computer. 我在nodejs文件中使用npm multer模块从客户端获取formdata,该数据包含我从计算机上传的图像。 However, when I try to print out the file on the server side, it is undefined, which I'm guessing that the file wasn't actually sent to the server. 但是,当我尝试在服务器端打印该文件时,它是未定义的,我猜测该文件实际上并未发送到服务器。 When I print it out on the client side, it is there. 当我在客户端打印出来时,它就在那里。

main.js (clientside) main.js(客户端)

var formData = new FormData();
formData.append("image", file);
var r = new XMLHttpRequest();
r.open("POST", "/post");
r.send(formData);

app.js (server side) app.js(服务器端)

var multer = require('multer');

var upload = multer({dest:'./pics/'});

app.post('/post', function(req, res) {
    console.log(req.files);

}

You have to actually use the middleware. 您必须实际使用中间件。 For example: 例如:

app.post('/post', upload.single('image'), function(req, res) {
  console.log(req.file);
});

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

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