【发布时间】:2022-01-16 06:26:30
【问题描述】:
我想使用 NodeJS 流和 HTML 表单上传文件。我有一个简单的服务器。 当我使用 Postman 上传文件时它正在工作。但是当我通过 HTML 表单上传时,文件已上传但不可读。怎么做?
这是index.js:
const app = require('express')();
const fs = require('fs');
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/file-upload', (req, res) => {
const filePath = 'uploads/uploaded-file';
const stream = fs.createWriteStream(filePath);
req.pipe(stream);
stream.on('close', () => {
res.send({ status: 'success', filePath })
});
});
// Start server
app.listen(3000, () => console.log("The server is running at localhost:3000"));
这是index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h1>File Upload</h1>
<form method="post" action="/file-upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="upload">
</form>
</body>
</html>
【问题讨论】:
标签: node.js forms file-upload stream