1. 程式人生 > >nodejs +body parser接收 base64並儲存圖片

nodejs +body parser接收 base64並儲存圖片

1. 引用fs和body-parser(為了解析json以及請求base64串大小限制)

var log4js = require('log4js');
var fs = require("fs");
var bodyParser = require('body-parser');
...


app.use(bodyParser.urlencoded({ extended: true,limit :"50mb"}));
app.use(bodyParser.json({ limit: '50mb' }));


...




2. 接請求存圖片

app.post("/snap",
        function(req, res) {
            
            var logger = log4js.getLogger("webrtc");
            
            try {
                logger.debug(req.rawBody);
                var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, "");
                logger.debug(base64Data);


                var result = "ok";
                fs.writeFile("capture.png", base64Data, 'base64', function (err) {
                    logger.error(err);
                    result = err;
                });


                res.send(result);
            } catch (ex) {
                logger.error(ex);
                res.send(ex);
            }
          
        });