【问题标题】:How to save a file sent from NodeJS with POST如何使用 POST 保存从 NodeJS 发送的文件
【发布时间】:2019-07-08 18:18:27
【问题描述】:

我创建了以下函数来加载流文件。该流被发送到使用 POST 指定的地址。在目的地,我有另一个 NodeJS 服务,它使用 ExpressJS “捕获”这个 POST,但我不知道如何将文件保存到目的地。

我的 PC 上的 NodeJS:

function sendFileToRaspberry(filePath) {
    var options = {
        method: 'POST',
        url: 'http://x.x.x.x:8080/api/print',
        qs: {file: fs.createReadStream(filePath)},
        headers:
            {
                'cache-control': 'no-cache'
            }
    };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);

        console.log(body);
    });
}

我的 Raspberry 上的 NodeJS:

app.post('/api/print', function (req, res) {

    ORIGINAL_IP = req.ip.replace("::ffff:", '');
    console.log("Received a print request from: " + ORIGINAL_IP);

    // Test history data for /api/printer API
    var file = req.query.file;
    console.log("Test data: " + file);
    util.inspect(file);

});

但在控制台日志中我得到:

收到来自:y.y.y.y 的打印请求

测试数据:[object Object]

如何在 Rasp 上保存此文件?

【问题讨论】:

    标签: javascript node.js fs requestjs


    【解决方案1】:

    您可以使用 expressjs 中间件帮助程序,例如 express-fileuploadmulter

    我认为,您已经使用Multipart Form Uploads 通过 http POST 上传文件。

    客户端(您的 PC)

    function sendFileToRaspberry(filePath) {
        var options = {
            method: 'POST',
            url: 'http://x.x.x.x:8080/api/print',
            formData: {
                file: fs.createReadStream(filePath)
            },
            headers: {
                'cache-control': 'no-cache'
            }
        };
    
        request(options, function (error, response, body) {
            if (error) throw new Error(error);
    
            console.log(body);
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-04
      • 2021-12-22
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 2018-02-07
      • 2021-08-14
      相关资源
      最近更新 更多