我无法使用 fs.createWriteStream 和 req.pipe 上传文件



我读过这个教程并尝试过:
https://debugmode.net/2014/01/14/how-to-upload-file-in-node-js/

html:

<form action="/post-a-file" method="post" enctype="multipart/form-data" >
<input type="file" name="file" required>
</form>

app.js:

app.post("/post-a-file",  function (req, res){
var destinationFile = fs.createWriteStream(__dirname + "/movies");
req.pipe(destinationFile)

req.on('end', ()=>{ console.log("end") })
})

但是在CCD_ 1中没有文件。

您不能用这种方式。您的帖子是以multipart/form-data的形式到达的,您需要中间件来为您解析它。然后,该中间件可能会为您提供将生成的文件数据放入文件中的选项。有关该中间件的一个选项,请参见multer。如果您只是上传一个文件,那么您可能想要使用multer的upload.single()变体。

最新更新