My code:
var express = require("express");
var bodyParser = require("body-parser");
var multer = require("multer");
var fs = require("fs");
var ejs = require('ejs');
var app = express();
var upload = multer({ dest: 'uploads/' })
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', function(req, res){
console.log('Works');
res.render('index');
});
app.post('/', upload.single('test'), function (req, res, next) {
var raw = new Buffer(req.file.buffer.toString(), 'base64');
fs.writeFile('./uploads/upload.png', raw, function (err) {
if (err) {
console.log('Error');
return next(err);
}
res.end('Success!');
});
});
var server = app.listen(3000, function() {
console.log("Listening on port %s...", server.address().port);});
My error:
TypeError: Cannot read property 'buffer' of undefined
at /Users/jacob/nodejs-prj/polyglotdev-test/app.js:27:33
at Layer.handle [as handle_request] (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/route.js:137:13)
at multerMiddleware (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/multer/lib/make-middleware.js:18:41)
at Layer.handle [as handle_request] (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/layer.js:95:5)
at /Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/jacob/nodejs-prj/polyglotdev-test/node_modules/express/lib/router/index.js:335:12)
I have to receive image file as base64 format from rasperry pi. Then i have to decode it back to image and save it in mongo db. I was trying to send some test data with postman to my endpoint. But always this error occurs. In Postman it looks likes this: Screenshot of postman
enctype="multipart/form-data"on your form?