上传文件到Node JS服务器

7

我正在尝试使用Express将文件上传到我的Node.js服务器。 这是我的Node.js代码:

var express=require('express');
var app=express();
var fs=require('fs');
var sys=require('sys');
app.listen(8080);
app.get('/',function(req,res){
fs.readFile('upload.html',function (err, data){
    res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
    res.write(data);
    res.end();
});



});
app.post('/upload',function(req,res)
{
console.log(req.files);
fs.readFile(req.files.displayImage.path, function (err, data) {
  // ...
  var newPath = __dirname;
  fs.writeFile(newPath, data, function (err) {
    res.redirect("back");
  });
});

});

我的 upload.html 文件:

<html>
<head>
<title>Upload Example</title>
</head>
<body>

<form id="uploadForm"
      enctype="multipart/form-data"
      action="/upload"
      method="post">
  <input type="file" id="userPhotoInput" name="displayImage" />
  <input type="submit" value="Submit">
</form>

<span id="status" />
<img id="uploadedImage" />


</body>
</html>

我遇到了一个错误,提示req.files未定义。可能出了什么问题?文件上传也无法正常工作。

1个回答

10

文档所述,req.filesreq.body一起由bodyParser中间件提供。您可以像这样添加中间件:

app.use(express.bodyParser());

// or, as `req.files` is only provided by the multipart middleware, you could 
// add just that if you're not concerned with parsing non-multipart uploads, 
// like:
app.use(express.multipart());

非常感谢。我不应该错过那个。 - Shubham Tripathi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接