首页 > 解决方案 > Nodejs Express 文本文件上传,没有 multer、busboy 或任何其他 npm

问题描述

我有一个多行文本文件,我想通过 http 帖子在我的 nodejs 应用程序中接收它。

我不想发送多部分表单数据,我不想使用额外的包,例如 multer 或 busboy 或 express-fileupload。只是绝对的基本文件上传。保留换行符。

const express = require('express')
const http = require('http')
const app = express()

app.post('/postTextFile', function(req, res, next) {
...
})

var server = http.createServer(app)
server.listen(5002,'localhost')

我这样发送:

curl -X POST -H "Content-Type: text/plain" --d @./test.txt http://localhost:5002/postTextFile

文件是:

ABC
DEF
GHI

标签: node.js

解决方案


您可以直接读取数据。

您的节点服务器:

const express = require('express');
const http = require('http');
const app = express();

app.post('/postTextFile', function(req, res, next) {
   let data = '';
   req.on('data', function(chunk) { data += chunk; });
   req.on('end', function() {
       console.log(data);
       res.sendStatus(200);
   });
});

var server = http.createServer(app);

server.listen(5002, 'localhost');

您的请求(用于--data-binary保留多行):

curl -X POST -H "Content-Type: text/plain" --data-binary "@./test.txt" http://localhost:5002/postTextFile

在服务器上,你得到:

ABC
DEF
GHI

推荐阅读