【问题标题】:How to upload a file using node js streams and HTML forms?如何使用节点 js 流和 HTML 表单上传文件?
【发布时间】: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


    【解决方案1】:

    如您所见,您正在尝试使用multipart/form-data 通过表单上传文件,而您在邮递员中将其上传为binary

    要解决此问题,您可以在服务器端设置 multipart/form-data 解析器(例如使用 multer),如下所示:

    const multer  = require('multer')
    const upload = multer({ dest: 'uploads/' })
    // ...
    
    app.post('/file-upload', upload.single('file'), (req, res) => {
        res.send({ status: 'success', filePath: req.file.path })        
    });
    

    【讨论】:

    • @martinho:有什么反馈吗?
    猜你喜欢
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2016-06-29
    • 2014-09-11
    • 1970-01-01
    • 2019-06-08
    相关资源
    最近更新 更多