I have created a directory to save images into when I attempt to upload a picture I get the error message Cannot POST /
I have tried changing the directory name in the code
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('weblinksDB');
var multer = require('multer');
var upload = multer();
db.serialize(function() {
db.run("CREATE TABLE IF NOT EXISTS weblinks (url TEXT, rating INTEGER)");
db.run("DELETE FROM weblinks");
db.run("INSERT INTO weblinks (url, rating) VALUES (?, ?)","http://www.bbc.co.uk",6);
db.run("INSERT INTO weblinks (url, rating) VALUES (?, ?)","http://bbc.com",10);
});
var express = require('express');
var restapi = express();
restapi.post('/insert', upload.array(), function (req, res, next) {
console.log(req.body.url);
console.log(req.body.rating);
db.run("INSERT INTO weblinks (url,rating) VALUES (?, ?)", req.body.url, req.body.rating, function (error) {
if (error) {
console.err(error);
res.status(500);
} else {
res.status(202);
}
res.end();
});
restapi.post('/', multer({ dest: './surfcata/uploads'}).single('upload'), function(req,res){
console.log(req.body);
console.log(req.file);
console.log(req.file.originalname); //shows the original name in cli
res.status(204).end();
});
});
the file should upload to the directory
Firstly, why you are putting your POST: '/' call inside POST: '/insert' call? Secondly, you can do something like:
var path = require('path');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './surfcata/uploads');
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname)); //Appending extension
}
});
var upload= multer({ storage: storage });
router.post('/add', upload.single('mainimage'), function (req, res, next) {
if (!req.file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
return new Error('Only image files are allowed!');
}
if(req.file.fieldname=== 'mainimage') {
var mainImageOriginalName= req.file.originalname;
mainImageName= req.file.filename;
var mainImageMime= req.file.mimetype;
var mainImagePath= req.file.path;
var mainImageExt= req.file.extension;
var mainImageSize= req.file.size;
} else {
mainImageName= 'noimage.png';
}
});
See if it helps!