如何将图像文件接收到api服务器(Node.js)

时间:2016-09-27 09:48:34

标签: node.js api curl

我想通过node.js构建api服务器 我想将图像文件发布到我的api服务器。

我能够在我的代码中编写GET方法逻辑 但是,我不知道写POST方法逻辑 请帮助我

↓我的代码(node.js)

// preprocessing
  // import library
  var express    = require('express');
  var app        = express();
  var bodyParser = require('body-parser');
  var fs         = require('fs');
  // post setting
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(bodyParser.json());
  // port setting
  var port = process.env.PORT || 3000;
  // express setting
  var router = express.Router();
  router.use(function(req, res, next) {
      console.log('Something is happening.');
      next();
  });

// main
 // GET method
 router.get('/', function(req, res) {
     res.json({ message: 'Hello World' });
 });
 // POST method
 router.route('/image')
  .post(function(req1, res1) { 
      res1.json({image : req1.body});
   });

  // routing
  app.use('/api/v1', router);
  // start server
  app.listen(port);
  console.log('listen on port ' + port);

↓tes curl命令(GET)

curl -k -x GET "http://XXX/api/v1"  

↓卷曲结果(GET)

"message" :"Hello World"

↓test curl command(POST)

curl -k -X POST -F "images_file=@test01.jpg" "http://XXXX/api/v1/image"

↓卷曲结果(POST)

"image" :""

1 个答案:

答案 0 :(得分:0)

客户端

<form action="/pictures/upload" method="POST" enctype="multipart/form-data">
  Select an image to upload:
  <input type="file" name="image"> 
  <input type="submit" value="Upload Image">
</form>

服务器端使用multer包并写下发布路由如下

var express = require('express')
  , router = express.Router()
  , multer = require('multer')

var uploading = multer({
  dest: __dirname + '../public/uploads/',
})

router.post('/upload', uploading, function(req, res) {

})

module.exports = router

for more detail take a look at this link image example