如何使用POST保存从NodeJS发送的文件
我创建了以下函数来加载流文件。此流将发送到POST指定的地址。在目的地,我有另一个NodeJS服务,ExpressJS“捕获”此POST,但我不知道如何将文件保存到目的地。
我的电脑上的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上保存此文件?
回答如下:您可以使用像express-fileupload
,multer这样的expressjs中间件帮助程序。
我想,您已经使用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);
});
}