使用 NodeJS 在 API 调用中上传文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8824130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use NodeJS to upload file in an API call
提问by Matt Gaunt
I'm looking at using NodeJS to act as the server to build an API.
我正在考虑使用 NodeJS 作为服务器来构建 API。
Ideally I'd love for there to be an API endpoint to send a set of information as well as a file which can be saved to the files system.
理想情况下,我希望有一个 API 端点来发送一组信息以及一个可以保存到文件系统的文件。
Most examples I've seen are for sending a file via a form, however I'd like to do this through a post request.
我见过的大多数示例都是通过表单发送文件,但是我想通过发布请求来做到这一点。
Does anyone know how I could achieve this (if it's at all possible)?
有谁知道我如何实现这一目标(如果可能的话)?
At the moment what I'd like to achieve is something along the following lines:
目前,我想实现的是以下几方面的内容:
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('') );
})
}
But the data and end never get called if I run a curl command along the lines of:
但是,如果我按照以下方式运行 curl 命令,则永远不会调用数据和结束:
curl http://127.0.0.1:5000/Some/Endpoint/ -F 'test=@test_file'
Cheers, Matt
干杯,马特
采纳答案by Matt Gaunt
The answer seems to be that expressJS doesn't use the same method of handling a post file as the http module in nodejs.
答案似乎是 expressJS 没有使用与 nodejs 中的 http 模块相同的处理 post 文件的方法。
All that was needed was including a directory for the files to be written to:
所需要的只是为要写入的文件包含一个目录:
app.use(express.bodyParser({uploadDir:'./uploads'}));
Which I found here:
我在这里找到的:
http://www.hacksparrow.com/handle-file-uploads-in-express-node-js.html
http://www.hacksparrow.com/handle-file-uploads-in-express-node-js.html
回答by piggyback
I would suggest you to use Formidableto avoid anonymous file uploading.
我建议您使用Formidable来避免匿名文件上传。
回答by maerics
Your code should work fine; it's the curl usage that's wrong. Try this instead:
您的代码应该可以正常工作;这是错误的 curl 用法。试试这个:
$ curl -X POST --data-binary @test_file http://localhost:8080

