使用NodeJS在API调用中上传文件

Mat*_*unt 13 node.js

我正在寻找使用NodeJS作为构建API的服务器.

理想情况下,我希望有一个API端点来发送一组信息以及一个可以保存到文件系统的文件.

我见过的大多数示例都是通过表单发送文件,但是我想通过发布请求来执行此操作.

有谁知道我怎么能做到这一点(如果可能的话)?

目前我想要达到的目标是以下几点:

app.post('/Some/Endpoint/', controller.handleSomeEndpoint, function(request, response) {
    response.send('Finished Request');
});

exports.handleSomeEndpoint = function(request, response, next) {
    var bodyarr = []
    request.on('data', function(chunk){
      bodyarr.push(chunk);
    })
    request.on('end', function(){
      console.log( bodyarr.join('') );
    })
}
Run Code Online (Sandbox Code Playgroud)

但是如果我按照以下方式运行curl命令,则数据和结束永远不会被调用:

curl http://127.0.0.1:5000/Some/Endpoint/ -F 'test=@test_file'
Run Code Online (Sandbox Code Playgroud)

干杯,马特

Mat*_*unt 5

答案似乎是expressJS不使用与nodejs中的http模块相同的处理post文件的方法.

所需要的只是包括要写入的文件的目录:

app.use(express.bodyParser({uploadDir:'./uploads'}));
Run Code Online (Sandbox Code Playgroud)

我在这里找到的:

http://www.hacksparrow.com/handle-file-uploads-in-express-node-js.html